Why is the replace all method not working? - java

I am testing out the replaceAll() method of the String class and I am having problems with it.
I do not understand why my code does not replace whitespaces with an empty string.
Here's my code:
public static void main(String[] args) {
String str = " I like pie!#!#! It's one of my favorite things !1!!!1111";
str = str.toLowerCase();
str = str.replaceAll("\\p{Punct}", "");
str = str.replaceAll("[^a-zA-Z]", "");
str = str.replaceAll("\\s+", " ");
System.out.print(str);
}
Output:
ilikepieitsoneofmyfavoritethings

The problem is there are no whitespaces in your String after this:
str = str.replaceAll("[^a-zA-Z]", "");
which replaces all characters that are not letters, which includes whitespaces, with a blank (effectively deleting it).
Add whitespace to that character class so they don't get nuked:
str = str.replaceAll("[^a-zA-Z\\s]", "");
And this line may be deleted:
str = str.replaceAll("\\p{Punct}", "");
because it's redundant.
Final code:
String str = " I like pie!#!#! It's one of my favorite things !1!!!1111";
str = str.toLowerCase();
str = str.replaceAll("[^a-zA-Z\\s]", "");
str = str.replaceAll("\\s+", " ");
System.out.print(str);
Output:
i like pie its one of my favorite things
You may want to add str = str.trim(); to remove the leading space.

Related

Change all letters except space from a string using Java

I want to change all letters from a string to "-" char except space using Java.
I tried:
String out = secretWord.replaceAll("^ " , "-");
and
String out = secretWord.replaceAll("\\s" , "-");
They didn't work.
I tried:
String newWord = secretWord.replaceAll("[A-Z]" , "-");
It worked but i didn't change Turkish characters I use in that string.
Original Code:
public class ChangeToLine {
public static void main(String[] args) {
String originalWord = "ABİDİKUŞ GUBİDİKUŞ";
String secretWord = originalWord;
}
}
You can use the \\S regex:
String s = "Sonra görüşürüz";
String replaced = s.replaceAll("\\S", "-");
System.out.println(replaced); // outputs ----- ---------
Use a character class
String out = secretWord.replaceAll("[^ ]" , "-");
or a capital S, instead of a lower s to replace all non space chars
String out2 = secretWord.replaceAll("\\S" , "-");
NOT needs to be expressed in square brackets in java.util.regex.Pattern:
String out = secretWord.replaceAll("[^\\s]", "-")

Need to remove extra square brackets in the string

static ArrayList<String> coordinates = new ArrayList<String>();
static String str = "";
static ArrayList scribbles = new ArrayList();
coordinates.add("String to be placed, String not to be placed");
String codChange = coordinates.toString().replaceAll(", ", "");
StringBuffer sb = new StringBuffer(codChange);
sb.insert(1,"m ");
ArrayList aListNumbers = new ArrayList(Arrays.asList(sb.toString()));
System.out.println("Coordinates: " + aListNumbers.toString().replaceAll("\\[|\\]", ""));
scribbles.add(aListNumbers);
str = scribbles.toString();
System.out.println("String: " + str);
OUTPUT:
Coordinates: m String to be placedString not to be placed
String: [[m String to be placedString not to be placed]]
I want the String: to appear with single square brackets like:
String: [m String to be placedString not to be placed]
Since there are two different replacement required.
Use below code
String s = "[[m String to be placedString not to be placed]]";
System.out.println(s.replaceAll("[[","[").replaceAll("]]","]");
If you are sure about always the exact position of [[ is at the beginning and ]] is at end, just use substring as suggested in the other answer in the same SO answer thread.

How to replace or convert the first occurrence of a dot from a string in java

Example:
Input
Str = P.O.Box
Output
Str= PO BOX
I can able to convert the string to uppercase and replace all dot(.) with a space.
public static void main(String args[]){
String s = "P.O.Box 1836";
String uppercase = s.toUpperCase();
System.out.println("uppercase "+uppercase);
String replace = uppercase.replace("."," ");
System.out.println("replace "+replace);
}
System.out.print(s.toUpperCase().replaceFirst("[.]", "").replaceAll("[.]"," "));
If you look the String API carefully, you would notice that there's a methods that goes by:-
replaceFirst(String regex, String replacement)
Hope it helps.
You have to use the replaceFirst method twice. First for replacing the . with <nothing>. Second for replacing the second . with a <space>.
String str = "P.O.Box";
str = str.replaceFirst("[.]", "");
System.out.println(str.replaceFirst("[.]", " "));
This one liner should do the job:
String s = "P.O.Box";
String replace = s.toUpperCase().replaceAll("\\.(?=[^.]*\\.)", "").replace('.', ' ');
//=> PO BOX
String resultValue = "";
String[] result = uppercase.split("[.]");
for (String value : result)
{
if (value.toCharArray().length > 1)
{
resultValue = resultValue + " " + value;
}
else
{
resultValue = resultValue + value;
}
}
Try this
System.out.println("P.O.Box".toUpperCase().replaceFirst("\\.","").replaceAll("\\."," "));
Out put
PO BOX
NOTE: \\ is needed here if you just use . only your out put will blank.
Live demo.
You should use replaceFirst method twice.
String replace = uppercase.replace("\\.", "").replaceFirst("\\.", "");
As you want to remove the first dot and replace the second one with a space, you need replace the whole P.O. section
Use
replace("P\\.O\\.", "PO ");

Android - Editing my String so each word starts with a capital

I was wondering if someone could provide me some code or point me towards a tutrial which explain how I can convert my string so that each word begins with a capital.
I would also like to convert a different string in italics.
Basically, what my app is doing is getting data from several EditText boxes and then on a button click is being pushed onto the next page via intent and being concatenated into 1 paragraph. Therefore, I assume I need to edit my string on the intial page and make sure it is passed through in the same format.
Thanks in advance
You can use Apache StringUtils. The capitalize method will do the work.
For eg:
WordUtils.capitalize("i am FINE") = "I Am FINE"
or
WordUtils.capitalizeFully("i am FINE") = "I Am Fine"
Here is a simple function
public static String capEachWord(String source){
String result = "";
String[] splitString = source.split(" ");
for(String target : splitString){
result
+= Character.toUpperCase(target.charAt(0))
+ target.substring(1) + " ";
}
return result.trim();
}
The easiest way to do this is using simple Java built-in functions.
Try something like the following (method names may not be exactly right, doing it off the top of my head):
String label = Capitalize("this is my test string");
public String Capitalize(String testString)
{
String[] brokenString = testString.split(" ");
String newString = "";
for(String s : brokenString)
{
s.charAt(0) = s.charAt(0).toUpper();
newString += s + " ";
}
return newString;
}
Give this a try, let me know if it works for you.
Just add android:inputType="textCapWords" to your EditText in layout xml. This wll make all the words start with the Caps letter.
Strings are immutable in Java, and String.charAt returns a value, not a reference that you can set (like in C++). Pheonixblade9's will not compile. This does what Pheonixblade9 suggests, except it compiles.
public String capitalize(String testString) {
String[] brokenString = testString.split(" ");
String newString = "";
for (String s : brokenString) {
char[] chars = s.toCharArray();
chars[0] = Character.toUpperCase(chars[0]);
newString = newString + new String(chars) + " ";
}
//the trim removes trailing whitespace
return newString.trim();
}
String source = "hello good old world";
StringBuilder res = new StringBuilder();
String[] strArr = source.split(" ");
for (String str : strArr) {
char[] stringArray = str.trim().toCharArray();
stringArray[0] = Character.toUpperCase(stringArray[0]);
str = new String(stringArray);
res.append(str).append(" ");
}
System.out.print("Result: " + res.toString().trim());

removing space before new line in java

i have a space before a new line in a string and cant remove it (in java).
I have tried the following but nothing works:
strToFix = strToFix.trim();
strToFix = strToFix.replace(" \n", "");
strToFix = strToFix.replaceAll("\\s\\n", "");
myString.replaceAll("[ \t]+(\r\n?|\n)", "$1");
replaceAll takes a regular expression as an argument. The [ \t] matches one or more spaces or tabs. The (\r\n?|\n) matches a newline and puts the result in $1.
try this:
strToFix = strToFix.replaceAll(" \\n", "\n");
'\' is a special character in regex, you need to escape it use '\'.
I believe with this one you should try this instead:
strToFix = strToFix.replace(" \\n", "\n");
Edit:
I forgot the escape in my original answer. James.Xu in his answer reminded me.
Are you sure?
String s1 = "hi ";
System.out.println("|" + s1.trim() + "|");
String s2 = "hi \n";
System.out.println("|" + s2.trim() + "|");
prints
|hi|
|hi|
are you sure it is a space what you're trying to remove? You should print string bytes and see if the first byte's value is actually a 32 (decimal) or 20 (hexadecimal).
trim() seems to do what your asking on my system. Here's the code I used, maybe you want to try it on your system:
public class so5488527 {
public static void main(String [] args)
{
String testString1 = "abc \n";
String testString2 = "def \n";
String testString3 = "ghi \n";
String testString4 = "jkl \n";
testString3 = testString3.trim();
System.out.println(testString1);
System.out.println(testString2.trim());
System.out.println(testString3);
System.out.println(testString4.trim());
}
}

Categories