I have a string like this:
mysz = \"name=john age=13 year=2001\";
I want to remove the whitespaces in the string. I tried trim()
mysz = mysz.replace(" ","");
First with space, second without space.
Then it is done.
When using st.replaceAll("\\s+","")
in Kotlin, make sure you wrap "\\s+"
with Regex:
"myString".replace(Regex("\\s+"), "")
If you prefer utility classes to regexes, there is a method trimAllWhitespace(String) in StringUtils in the Spring Framework.
Use mysz.replaceAll("\\s+","");
White space can remove using isWhitespace function from Character Class.
public static void main(String[] args) {
String withSpace = "Remove white space from line";
StringBuilder removeSpace = new StringBuilder();
for (int i = 0; i<withSpace.length();i++){
if(!Character.isWhitespace(withSpace.charAt(i))){
removeSpace=removeSpace.append(withSpace.charAt(i));
}
}
System.out.println(removeSpace);
}
public static void main(String[] args) {
String s = "name=john age=13 year=2001";
String t = s.replaceAll(" ", "");
System.out.println("s: " + s + ", t: " + t);
}
Output:
s: name=john age=13 year=2001, t: name=johnage=13year=2001