Luke C
Luke C

Reputation: 158

How to get single occurrences of only certain characters?

I have the following code to pick find any two of the same letters next to each other and remove one.

For example: singleOccurrence("1//2/2018")

My code:

public static StringBuilder singleOccurrence(String s) {
    StringBuilder sb = new StringBuilder();
    if (s.length() > 0) {
        char prev = s.charAt(0);
        sb.append(prev);
        for (int i = 1; i < s.length(); ++i) {
            char cur = s.charAt(i);
            if (cur != prev) {
                sb.append(cur);
                prev = cur;
            }
        }
    }
    return sb;
}

This will return: "1/2/2018"

However, if I inputted: singleOccurrence("11//2/2018") It would return: "1/2/2018"

Notice that my method removes double occurrences of all characters.

My question is how do I make my method only do what it's supposed to do with the characters "/", "-", ":"

Thanks in advance :)

Upvotes: 0

Views: 44

Answers (2)

Tung Tran
Tung Tran

Reputation: 2955

public void singleOccurrence(String string) 
{
    char[] chars = string.toCharArray();
    List<Character> characters = new ArrayList<>();
    char temp = 0;
    for (char c : chars) {
        if (temp != c || (c != '/' && c != '_' && c != ':')) {
            characters.add(c);
        }
        temp = c;
    }

    StringBuilder sb = new StringBuilder();
    for (Character character : characters) {
        sb.append(character);
    }

    Log.e(TAG, sb.toString());
}

Hope it can help you!

Upvotes: 1

rarejewel
rarejewel

Reputation: 26

Add this into your if statement. That checks if prev & cur characters are not '-' '/' or ':' append to result.

if (cur != prev || (cur != '-' || cur != '/' || cur != ':')) 
{
   sb.append(cur);
   prev = cur;
 }

Upvotes: 1

Related Questions