Cammo5000
Cammo5000

Reputation: 3

finding words within String and returning as String + spaces Java

I've been practicing on Codewars to improve my programming but am stuck on this problem, i.e.:

-need to go through a String and take out the "Wub" and "Dub" in order to

-present the English language words inside the String

-in a String separated by a space

eg. The output here should be: we are the champions my friends

I find myself unable to -convert the Character array list into a string adequately -identify the words and separate by a space

I hope I've explained this adequately, thanks in advance.

public class Dubstep {

public static void main(String[] args) {
    System.out.println(SongDecoder("WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB"));
}

public static String SongDecoder(String song) {
    String name = song;
    ArrayList<Character> words = new ArrayList<Character>();
    for (int i = 0; i < song.length(); i++) {

        if (name.charAt(i) == 'W' && name.charAt(i + 1) == 'U' && name.charAt(i + 2) == 'B') {
            i = i + 2;
        } else { 
             words.add(name.charAt(i));
        }
    }
    String result = words.toString();
    return result;
}
}
///expected:
///we are the champions my friends
///actual:
///[W, E, A, R, E, T, H, E, C, H, A, M, P, I, O, N, S, M, Y, F, R, I, E, N, D]

Solution offered:

public class dubStepv2 {

public static void main(String[] args) {
    System.out.println(SongDecoder("WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB"));
}
public static String SongDecoder(String song) {
    String originalString = song;

    String newString = originalString.replace("WUB", " ");
   newString = newString.replace("DUB", " ");
    newString = newString.trim();

    return newString;
}
}
///Output:
///WE ARE  THE CHAMPIONS MY FRIEND
///Expected:
///WE ARE THE CHAMPIONS MY FRIEND

Upvotes: 0

Views: 116

Answers (1)

Scary Wombat
Scary Wombat

Reputation: 44844

A very much simpler way would be to use String::replace and String::trim

newString = "WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB"
        .replace("WUB", " ")
        .replace("DUB", " ")
        .trim();

replacing with a blank and to remove leading and trailing blanks.

Upvotes: 2

Related Questions