简体   繁体   English

java字符串删除空格并添加字母

[英]java String remove spaces and add letter

If someone have idea how can i accomplish this. 如果有人知道我该怎么做。 Lets say i have one string: 可以说我有一个字符串:

String word = " adwq ijsdx djoaaiosj  czxc  f  wqeqw xcx  ";

I want to remove spaces and put before every word some another symbol or letter? 我要删除空格,并在每个单词前加上另一个符号或字母吗? So i can get something like this: 所以我可以得到这样的东西:

String newWord ="$adwq $ijsdx $djoaaiosj $czxc $f $wqeqw $xcx";

I tried something like this: 我尝试过这样的事情:

String newWord = word.replaceAll("\\s+"," ").replaceAll(" "," $");

and i get something like this :( 我得到这样的东西:(

String newWord = $adwq $ijsdx $djoaaiosj $czxc $f $wqeqw $xcx $";

And how t detect if in string are multiple same words. 以及如何检测字符串中是否有多个相同的单词。

// replace one or more spaces followed by a word boundary with space+dollar sign:
String newWord = word.replaceAll("\\s+\\b"," $").trim();

Here what I would do: 在这里我会做什么:

    newWord = newWord.trim(); // This would remove trailing and leading spaces
    String [] words = newWord.split("\\s+"); //split them on spaces
    StringBuffer sb = new StringBuffer();
    for(int i=0;i<words.length-1;i++){
        sb.append('$');
        sb.append(words[i]);
        sb.append(' ');
    }
    if(words.length>0){
        sb.append('$');
        sb.append(words[words.length-1]);
    }
    newWord = sb.toString();

For your other question you can have a locale HashSet and check if each word has been already added there or not. 对于您的其他问题,您可以使用语言环境HashSet并检查是否已在其中添加每个单词。

Trim the string first, and combine your replaceAll calls: 首先修剪字符串,然后合并您的replaceAll调用:

String word = " adwq ijsdx djoaaiosj  czxc  f  wqeqw xcx  ";
String newWord = word.trim().replaceAll("^\\b|\\s*(\\s)", "$1\\$");
System.out.println("'" + word + "'");
System.out.println("'" + newWord + "'");

Output 输出量

' adwq ijsdx djoaaiosj  czxc  f  wqeqw xcx  '
'$adwq $ijsdx $djoaaiosj $czxc $f $wqeqw $xcx'

Explanation 说明

The trim() call will remove leading and trailing spaces: trim()调用将删除前导和尾随空格:

"adwq ijsdx djoaaiosj  czxc  f  wqeqw xcx"

The regex contains two expressions separated by | 正则表达式包含两个由|分隔的表达式 ( or ). or )。 The second ( \\\\s*(\\\\s) ) will replace a sequence of spaces with the space ( $1 ) and a dollar sign ( \\\\$ ): 第二个( \\\\s*(\\\\s) )将用空格( $1 )和美元符号( \\\\$ )替换一系列空格:

"adwq $ijsdx $djoaaiosj $czxc $f $wqeqw $xcx"

The first expression ( ^\\\\b ) will replace a word boundary at the beginning of the string with a dollar sign (no space because $1 is empty): 第一个表达式( ^\\\\b )将用美元符号替换字符串开头的单词边界(没有空格,因为$1为空):

"$adwq $ijsdx $djoaaiosj $czxc $f $wqeqw $xcx"

This guards against the empty string, where " " should become "" . 这可以防止空字符串" "应成为""

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

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