Originally, I was just trying to get the characters in a string. I used split to isolate my characters to count them. I have my characters, but I can't get rid of the spaces it's printing in the array.
I tried everything that I saw in other stack overflow posts.
public class Test {
public static void main(String[] args) {
String str = "+d+=3=+s+";
String[] alpha = str.split("[^a-z]");
for(int i = 0; i < alpha.length; i++) {
alpha[i] = alpha[i].replaceAll("\\s+", "");
System.out.println(alpha[i]);
}
// System.out.println(alpha.length);
}
}
I'm just trying to count characters without spaces and using more loops.
Do this way
public class Test {
public static void main(String[] args) {
String str = "+d+=3=+s+";
System.out.println(str);
str = str.replaceAll("[^a-zA-Z]", "");
System.out.println(str);
System.out.println("count "+str.length());
}
}
Output will be
ds
count 2
output doesn't contains whitespace so you can get rid of loops
If you're referring to the blank lines in your output, those are not spaces , they are empty strings in the alpha
array.
Since you regex only matching a single character, the split
operation will create empty entries, ie a plain split will produce the following array:
{ "", "d", "", "", "", "", "s", "" }
Since split
by default removes trailing empty strings, what you actually get is:
{ "", "d", "", "", "", "", "s" }
As you can see, there are no spaces anywhere.
You can remove most of the empty strings by changing "[^az]"
to "[^az]+"
, so multiple consecutive non-letters will be a single separator, which will give you:
{ "", "d", "s" }
To remove the leading empty string, remove the leading non-letters from the original string first:
String[] alpha = str.replaceFirst("[^a-z]+", "").split("[^a-z]+");
That will give you:
{ "d", "s" }
Which of course will eliminate all the blank lines in your output:
d
s
And you can remove that replaceAll("\\\\s+", "")
call, since it's not doing anything.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.