简体   繁体   English

如何摆脱此String []中的空格?

[英]How do I get rid of the white spaces in this String[]?

Originally, I was just trying to get the characters in a string. 最初,我只是想让字符串中的字符。 I used split to isolate my characters to count them. 我使用split来隔离我的角色以计算它们。 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. 如果你指的是输出中的空行 ,那些不是空格 ,它们是alpha数组中的空字符串

Since you regex only matching a single character, the split operation will create empty entries, ie a plain split will produce the following array: 由于正则表达式只匹配单个字符,因此split操作将创建空条目,即普通拆分将生成以下数组:

{ "", "d", "", "", "", "", "s", "" }

Since split by default removes trailing empty strings, what you actually get is: 由于默认情况下split会删除尾随的空字符串,因此您实际得到的是:

{ "", "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: 您可以通过将"[^az]"更改为"[^az]+"来删除大多数空字符串,因此多个连续的非字母将是单个分隔符,这将为您提供:

{ "", "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. 你可以删除replaceAll("\\\\s+", "")调用,因为它没有做任何事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM