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 :)
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;
}