Dusan Krsmanovic
Dusan Krsmanovic

Reputation: 27

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.

Upvotes: 0

Views: 161

Answers (3)

Andreas
Andreas

Reputation: 159106

Trim the string first, and combine your replaceAll calls:

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:

"adwq ijsdx djoaaiosj  czxc  f  wqeqw xcx"

The regex contains two expressions separated by | (or). The second (\\s*(\\s)) will replace a sequence of spaces with the space ($1) and a dollar sign (\\$):

"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):

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

This guards against the empty string, where " " should become "".

Upvotes: 0

kris larson
kris larson

Reputation: 30985

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

Upvotes: 1

Amr
Amr

Reputation: 802

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.

Upvotes: 0

Related Questions