Mel Torment
Mel Torment

Reputation: 49

String iteration with numbers at the end (Beginner)

I have a code that "deletes" all characters in a sentence that appear more than once in a row. For example:

"Thiiis iiis aaa tesst"

I use the charAt() and length() method (It's a task for University and I am only allowed to use this two methods). In a way it works fine but my question is:

Why do I see numbers at the end of my sentence? And can anyone tell me if or where my code is wrong?

This is a test19212325272

Here is the code I used for this:

public static String reduce(String w) {
    String result = "";
    for (int i = 0; i < w.length() - 1; i++) {
        if(w.charAt(i) == w.charAt(i + 1)) {
            w += w.length() - 1;
        }
        else {
            result += w.charAt(i);
        } 
    }
    return result;
}

Thanks!

Upvotes: 0

Views: 32

Answers (3)

anoopknr
anoopknr

Reputation: 3355

This is because of w += w.length() - 1 .You don't need that.

Modified code :-

public static String reduce(String w) {
    if (w == null) return null;         // in case if w is NULL
    String result = "";
    result += w.charAt(0);
    for (int i = 1; i < w.length(); i++) {
        if (w.charAt(i - 1) != w.charAt(i)) {
            result += w.charAt(i);
        }
    }
    return result;
}

Output :-

Thiiis iiis aaa tesst
This is a test

Upvotes: 1

Yogen Rai
Yogen Rai

Reputation: 3033

You don't need if condition at all. The following program removes duplicate characters:

public static String reduce(String w) {
    // make sure w is not null
    if (w == null) return null;

    String result = Character.toString(w.charAt(0));
    for (int i = 1; i < w.length(); i++) {
        if(w.charAt(i) != w.charAt(i - 1)) {
            result += w.charAt(i);
        }
    }
    return result;
}

Upvotes: 0

szczeppan
szczeppan

Reputation: 34

It's because of w += w.length() - 1 when there are a two the same characters you are adding to w variable it length. When you remove it (and also add after for loop check if last char is the same like previous) then this code works perfectly fine

Upvotes: 0

Related Questions