I need some help parsing a string that is input to one that is later cleaned and output.
e.g.
String str = " tHis strIng is rEalLy mEssy "
and what I need to do is have it parsed from that to look like this:
"ThisStringIsReallyMessy"
so I basically need to clean it up then set only the first letter of every word to capitals, without having it break in case someone uses numbers.
Apache Commons to the rescue (again). As always, it's worth checking out the Commons libraries not just for this particular issue, but for a lot of functionality.
You can use Apache Commons WordUtils.capitalize() to capitalise each word within the string. Then a replaceAll(" ", "") will bin your whitespace.
String result = WordUtils.capitalize(str).replaceAll(" ", "");
Note (other) Brian's comments below re. the choices behind replace() vs replaceAll().
String[] tokens = " tHis strIng is rEalLy mEssy ".split(" ");
StringBuilder result = new StringBuilder();
for(String token : tokens) {
if(!token.isEmpty()) {
result.append(token.substring(0, 1).toUpperCase()).append(token.substring(1).toLowerCase());
}
}
System.out.println(result.toString()); // ThisStringIsReallyMessy
String str = " tHis strIng is rEalLy mEssy ";
str =str.replace(" ", "");
System.out.println(str);
output:
tHisstrIngisrEalLymEssy
For capitalizing first letter in each word there is no in-built function available, this thread has possible solutions.
Do you mean this?
str = str.replaceAll(" ", "");
Related
I currently have a for loop, and I am looking for a quick and elegant method to remove the plus sign + from the first "adding" of the loop, so the results is not +example+input+string but rather example+input+string preferably without the need of rewriting the loop much.
String inpputString = "example input string";
String outputString= "";
String[] stringPieces= mainString.split(" ");
for (String strTemp : stringPieces){
outputString = outputString + "+" + strTemp;
}
Based on the observation that you don't want a separator the first time - use an empty separator the first time!
String sep = "";
for (String strTemp : stringPieces) {
outputString += sep + strTemp;
sep = "+";
}
Personally, I would proffer the solution using String.join() proposed by #shmosel in the comment.
Here is another way of achieving this with Stream API:
String outputString =
Arrays.stream(stringPieces).collect(Collectors.joining("+"));
I am receiving a string from server trailing one or two lines of spaces like below given string.
String str = "abc*******
********";
Consider * as spaces after my string
i have tried a few methods like
str = str.trim();
str = str.replace(String.valueOf((char) 160), " ").trim();
str = str.replaceAll("\u00A0", "");
but none is working.
Why i am not able to remove the space?
You should try like this:
str = str.replaceAll("\n", "").trim();
You can observe there is a new line in that string . first replace new line "\n" with space("") and than trim
You should do:
str = str.replaceAll("\n", "");
In my case use to work the function trim()
Try this:
str = str.replaceAll("[.]*[\\s\t]+$", "");
I have tried your 3 methods, and them all work. I think your question describing not correctly or complete, in fact, a String in java would not like
String str = "abc*******
********";
They must like
String str = "abc*******"
+ "********";
So I think you should describe your question better to get help.
I am using the code in Java:
String word = "hithere";
String str = "123hithere12345hi";
output(str.replaceAll("(?!"+word+")", "x"));
However, rather than outputting: xxxhitherexxxxxxx like I want it to, it outputs: x1x2x3hxixtxhxexrxex1x2x3x4x5xhxix x, I've tried a load of different regex patterns to try to do this, but I can't seem to figure out how to do this :(
Any help would be much appreciated.
Well this technically works. Using only replace all and only one line, and it's assuming you string does not contain a deprecated ASCII character (BEL)
String string = "hithere";
String string2 = "asdfasdfasdfasdfhithereasasdf";
System.out.println(string2.replaceAll(string,"" + (char)string.length()).replaceAll("[^" + (char)string.length() + "]", "x").replaceAll("" + (char)string.length(), string));
I think this is what you're looking for, if I'm not mistaken:
String pattern = "(\\d)|(hi$)";
System.out.println("123hithere12345hi".replaceAll(pattern, "X"));
The pattern replaces any numeric digits and the word "hi".
This lookaround based code will work for you:
String word = "hithere";
String string = "123hithere12345hi";
System.out.println(string.replaceAll(
".(?=.*?\\Q" + word + "\\E)|(?<=\\Q" + word + "\\E(.){0,99}).", "x"));
//=> xxxhitherexxxxxxx
I am really confused on this regex things. I have tried to understand it, went no where.
Basically, i am trying to replace all spaces followed by every character but a space to be replaced with "PM".
" sd"
" sd"
however
" sd"
" sd"
This will replace the space and the following character with "PM":
String s = "123 axy cq23 dasd"; //your string
String newString = s.replaceAll(" [^ ]","PM");
Since I'm not sure if you want to replace only the space or the space and the following character, too, here is a slightly modified version that replaces only the space:
String s = "123 axy cq23 dasd"; //your string
String newString = s.replaceAll(" ([^ ])", "PM$1")
You need to use non-capturing pattern:
String res = oldString.replaceAll(" (?:[^ ])", "PM");
I have a code like,
String str = " " ;
while( cond ) {
str = str + "\n" ;
}
Now, I don't know why at the time of printing, the output string is not printing the newline character. However, when I add any other character like ( str = str + "c"), it is printing properly. Can anybody help me, how to solve this problem and why this happening ?
The newline character is considered a control character, which doesn't print a special character to the screen by default.
As an example, try this:
String str = "Hi";
while (cond) {
str += "\n"; // Syntactically equivalent to your code
}
str += "Bye";
System.out.println(str);
Looks like you are trying to run the above code on Windows. Well the line separator or new line is different on Windows ( '\r\n' ) and Unix flavors ('\n').
So, instead of hard coding and using '\n' as new line. Try getting new line from the system like:
String newLine = System.getProperty("line.separator");
String str = " " ;
while( cond ) {
str = str + newLine ;
}
If you really want \n, to get printed, do it like this.
String first = "C:/Mine/Java" + "\\n";
System.out.println(first);
OUTPUT is as follows :
For a good reference as to why is this happening, visit JAVA Tutorials
As referred in that TUTORIAL : A character preceded by a backslash is an escape sequence, and has a special meaning to the compiler. When an escape sequence is encountered in a print statement, the compiler interprets it accordingly
Hope this might help.
Regards
Based on your sample, the only reason it would not show a new line character is that cond is never true and thus the while loop never runs...