How to split String by taking space's in java - java

I know its very easy to split data in strings, but still i want guide to concate string,
my data is in the format. In my string the data is in the above format
104
inNetStandardGuest
windowsGuest
uestToolsTooOld
121
slesGuest
guestToolsTooOld
20569355609
Expected Output:
104,inNetStandardGuest,windowsGuest,uestToolsTooOld
121,slesGuest,guestToolsTooOld,20569355609

It's simply splitting and combining strings.
StringBuilder out = new StringBuilder();
for (String set : data.split("\n\n\n")) {
for (String line : set.split("\n")) {
out.append(line).append(',');
}
out.setCharAt(out.length(), '\n');
}
System.out.println(out);

With Guava's Splitter and Joiner:
final Iterable<String> lines = Splitter.on("\n\n\n").split(input);
for (final String line : lines) {
final Iterable<String> fields = Splitter.on("\n").split(line);
final String joined = Joiner.on(",").join(fields);
}

How about this?
String s = "104\n" +
"inNetStandardGuest\n" +
"windowsGuest\n" +
"uestToolsTooOld\n" +
"\n" +
"\n" +
"121\n" +
"slesGuest\n" +
"guestToolsTooOld\n" +
"20569355609\n";
System.out.println(s.replaceAll("(.)\\n","$1,")
.replaceAll(",,","\n")
.replaceAll(",\\n","\n"));
Probably not the most efficient way, though.

Buffered reader:
http://docs.oracle.com/javase/1.4.2/docs/api/java/io/BufferedReader.html
readLine() method:
http://docs.oracle.com/javase/1.4.2/docs/api/java/io/BufferedReader.html#readLine()
For example you read 4 lines
string outputLine = line1 + "," + line2 + "," + line3 + "," + line4;
Then read 2 lines and skip it.
If you don't know how to implement it using my advices, you should read
some basics tutorial.

Try this :
String str = "104\ninNetStandardGuest\nwindowsGuest\nuestToolsTooOld\n\n\n121\nslesGuest\nguestToolsTooOld\n20569355609";
str= str.replaceAll("\\s", ",").replaceAll(",,,", "\n");
System.out.println(str);
Output :
104,inNetStandardGuest,windowsGuest,uestToolsTooOld
121,slesGuest,guestToolsTooOld,20569355609

Related

Splitting array in string does not give last element

Hi I am splitting and storing string with use of array but does not give result
String str = "123456";
String[] arrOfStr = str.split("");
String otpnum1 = arrOfStr[0];
String otpnum2 = arrOfStr[1];
String otpnum3 = arrOfStr[2];
String otpnum4 = arrOfStr[3];
String otpnum5 = arrOfStr[4];
String otpnum6 = arrOfStr[5];
System.out.println("otp"+otpnum1+otpnum2+otpnum3+otpnum4+otpnum5+otpnum6);
OUTPUT
System.out: otp12345
You are printing without any space or newline, which is the reason you are not able to interpret individual variables. Use this
System.out.println("otp " + otpnum1+ " " + otpnum2+" " + " "+ otpnum3+ " " + otpnum4+ " " + otpnum5+ " " + otpnum6);
I understand, the output is 12345, and expected 123456 for the result.
But, looking your code looks like correct.
I have try your code here, for test, and works fine.
The output was: otp123456

Unwanted elements appearing when splitting a string with multiple separators in Java

I have a string from which I need to remove all mentioned punctuations and spaces. My code looks as follows:
String s = "s[film] fever(normal) curse;";
String[] spart = s.split("[,/?:;\\[\\]\"{}()\\-_+*=|<>!`~##$%^&\\s+]");
System.out.println("spart[0]: " + spart[0]);
System.out.println("spart[1]: " + spart[1]);
System.out.println("spart[2]: " + spart[2]);
System.out.println("spart[3]: " + spart[3]);
System.out.println("spart[4]: " + spart[4]);
But, I am getting some elements which are blank. The output is:
spart[0]: s
spart[1]: film
spart[2]:
spart[3]: fever
spart[4]: normal
My desired output is:
spart[0]: s
spart[1]: film
spart[2]: fever
spart[3]: normal
spart[4]: curse
Try with this:
public static void main(String[] args) {
String s = "s[film] fever(normal) curse;";
String[] spart = s.split("[,/?:;\\[\\]\"{}()\\-_+*=|<>!`~##$%^&\\s]+");
for (String string : spart) {
System.out.println("'"+string+"'");
}
}
output:
's'
'film'
'fever'
'normal'
'curse'
I believe it is because you have a Greedy quantifier for space at the end there. I think you would have to use an escape sequence for the plus sign too.
String spart = s.replaceAll( "\\W", " " ).split(" +");

How to remove commas at the end of any string

I have Strings "a,b,c,d,,,,, ", ",,,,a,,,,"
I want these strings to be converted into "a,b,c,d" and ",,,,a" respectively.
I am writing a regular expression for this. My java code looks like this
public class TestRegx{
public static void main(String[] arg){
String text = ",,,a,,,";
System.out.println("Before " +text);
text = text.replaceAll("[^a-zA-Z0-9]","");
System.out.println("After " +text);
}}
But this is removing all the commas here.
How can write this to achieve as given above?
Use :
text.replaceAll(",*$", "")
As mentioned by #Jonny in comments, can also use:-
text.replaceAll(",+$", "")
Your first example had a space at the end, so it needs to match [, ]. When using the same regular expression multiple times, it's better to compile it up front, and it only needs to replace once, and only if at least one character will be removed (+).
Simple version:
text = text.replaceFirst("[, ]+$", "");
Full code to test both inputs:
String[] texts = { "a,b,c,d,,,,, ", ",,,,a,,,," };
Pattern p = Pattern.compile("[, ]+$");
for (String text : texts) {
String text2 = p.matcher(text).replaceFirst("");
System.out.println("Before \"" + text + "\"");
System.out.println("After \"" + text2 + "\"");
}
Output
Before "a,b,c,d,,,,, "
After "a,b,c,d"
Before ",,,,a,,,,"
After ",,,,a"

java iterate over map except last iteration

I have the next map values:
{title=varchar(50), text=text}
I am trying to convert it into two strings like this:
StringBuffer string = new StringBuffer();
for (String keyinside: values.keySet()) {
string.append(keyinside + " " + values.get(keyinside) + ", ");
}
But what I want here - not inlude ", " at the last iteration. How can I do it?
Short java 8 alternative:
String result = values.entrySet().stream().map(e -> e.getKey() + " " + e.getValue())
.collect(Collectors.joining(", "))
Stream.map() to convert all entries in the map to a string description of the entry.
Note that Java 8 also finally adds the function String.join().
Use some indicator :
StringBuffer string = new StringBuffer();
boolean first = true;
for (String keyinside: values.keySet()) {
if (!first)
string.append (", ");
else
first = false;
string.append(keyinside + " " + values.get(keyinside));
}
BTW, it's more efficient to use StringBuilder (assuming you don't need thread safety).
I quite like Joiner from Google collections library. You could just do this:
on(",").withKeyValueSeparator(" ").join(values);
on is statically imported from com.google.common.base.Joiner.
If you use Maven, just add a dependency:
<dependency>
<groupId>com.google.collections</groupId>
<artifactId>google-collections</artifactId>
<version>1.0</version>
</dependency>
Take a counter which increments in every iteration and get a if condition which checks whether it is iterating the last time
A simple trick is
int i = 0 ;
for (String keyinside: values.keySet()) {
string.append(keyinside + " " + values.get(keyinside));
if((i+1)<values.keySet().size()){
string.append(", ");
}
i++;
}
Also I suggest you to use StringBuilder if thread safety is not a concern
You can try this .by which we can remove the comma(,) at end.
Hope this helps you.
Map<String,String> s= new LinkedHashMap<String,String>();
s.put("1", "A");
s.put("2", "B");
s.put("3", "C");
StringBuffer sb = new StringBuffer();
String ans=null;
for (String keyinside: s.keySet()) {
sb.append(keyinside + " " + s.get(keyinside) + ", ").toString();
}
System.out.println(sb);
ans=sb.substring(0, sb.length()-2).toString();
System.out.println(ans);
Note: you can refer How to remove the last character from a string?

Best way to split a string containing question marks and equals

Having an issue where I have a java string:
String aString="name==p==?header=hello?aname=?????lname=lastname";
I need to split on question marks followed by equals.
The result should be key/value pairs:
name = "=p=="
header = "hello"
aname = "????"
lname = "lastname"
The problem is aname and lname become:
name = ""
lname = "????lname=lastname"
My code simply splits by doing aString.split("\\?",2)
which will return 2 strings.One contains a key/value pair and the second string contains
the rest of the string. If I find a question mark in the string, I recurse on the second string to further break it down.
private String split(String aString)
{
System.out.println("Split: " + aString);
String[] vals = aString.split("\\?",2);
System.out.println(" - Found: " + vals.length);
for ( int c = 0;c<vals.length;c++ )
{
System.out.println(" - "+ c + "| String: [" + vals[c] + "]" );
if(vals[c].indexOf("?") > 0 )
{
split(vals[c]);
}
}
return ""; // For now return nothing...
}
Any ideas how I could allow a name of ?
Disclaimer: Yes , My Regex skills are very low, so I don't know if this could be done via a regex expression.
You can let regex do all the heavy lifting, first splitting your string up into pairs:
String[] pairs = aString.split("\\?(?!\\?)");
That regex means "a ? not followed by a ?", which gives:
[name==p==, header=hello, aname=????, lname=lastname]
To then also split the results into name/value, split only the first "=":
String[] split = pair.split("=", 2); // max 2 parts
Putting it all together:
String aString = "name==p==?header=hello?aname=?????lname=lastname";
for (String pair : aString.split("\\?(?!\\?)")) {
String[] split = pair.split("=", 2);
System.out.println(split[0] + " is " + split[1]);
}
Output:
name is =p==
header is hello
aname is ????
lname is lastname
You can try like this
String[] vals = "Hello??Man?HowAreYou????".split("\\?+");
System.out.println(vals[0]+vals[1]+vals[2]);
OUTPUT
HelloManHowAreYou
But as aname=????? you want to get you can replace the
????? Five Question Marks with Other Symbol and replace back to ????? after split
String processed="Hello????Good? ? ....???".replace("????","*");
OUTPUT
Hello*Good? ? ....???
And than use split for ?
Here the code, you are looking .
Implemented using the Split and HashMap.
Tested and Executed.
import java.util.HashMap;
import java.util.Map;
public class Sample {
public static void main(String[] args) {
// TODO Auto-generated method stub
// String[] vals = "Hello??Man?HowAreYou????".split("\\?+");
// System.out.println(vals[0]+vals[1]+vals[2]);
String query="name==p==?header=hello?aname=?????lname=lastname";
String[] params = query.split("\\?");
Map<String, String> map = new HashMap<String, String>();
for (String param : params)
{
String name = param.split("=")[0];
String value = param.substring(name.length(),param.length());
map.put(name, value);
System.out.println(name);
if(name.equals("")){
value+="?";
}
System.out.println(value.replaceAll(" ", ""));
}
}
}
I assume you are parsing URLs. The correct way would be to encode all special characters like ?, & and = which are values or names.
Better Solution: Encoding characters:
String name = "=p==";
String aname = "aname=????";
String lname = "lastname";
String url = "name=" + URLEncoder.encode(name, "UTF-8") +
"?aname=" + URLEncoder.encode(aname, "UTF-8") +
"?lname=" + URLEncoder.encode(lname, "UTF-8");
After that you have something like this:
name==p==?aname=?????lname=lastname
This can be splitted and decoded easily.
Other Solution: Bad input parsing:
If you insist, this works also. You can use a regex:
Pattern pattern = Pattern.compile("(\\w+?)=(\\S+?\\?+)");
Matcher m = pattern.matcher(query + "?");
while (m.find()) {
String key = m.group(1);
String value = m.group(2);
value = value.substring(0, value.length() - 1);
System.out.println(key + " = " +value);
}

Categories