简体   繁体   English

解析字符串以删除空格java

[英]parse string to remove spaces java

I need some help parsing a string that is input to one that is later cleaned and output. 我需要一些帮助来解析输入到稍后清理和输出的字符串的字符串。

eg 例如

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). Apache Commons拯救(再次)。 As always, it's worth checking out the Commons libraries not just for this particular issue, but for a lot of functionality. 与往常一样,值得查看Commons库,不仅仅是针对这个特定问题,还有很多功能。

You can use Apache Commons WordUtils.capitalize() to capitalise each word within the string. 您可以使用Apache Commons WordUtils.capitalize()来大写字符串中的每个单词。 Then a replaceAll(" ", "") will bin your whitespace. 然后一个replaceAll(" ", "")将你的空白分开。

String result = WordUtils.capitalize(str).replaceAll(" ", "");

Note (other) Brian's comments below re. 注意(其他)Brian的评论如下。 the choices behind replace() vs replaceAll() . replace() vs replaceAll()背后的选择。

   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. 为了使每个单词中的首字母大写,没有可用的内置函数,该线程有可能的解决方案。

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

你是说这个吗?

str = str.replaceAll(" ", "");

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

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