-4

If I have a string "SSSAAADDDCCC" how would I print just "SADC". Can it be done using SubString or would I have to use charAt()?

JStevez
  • 11
  • 2
  • 4

3 Answers3

1

There is a simple way to do this - however since I don't see any code and I do not see any effort on your part I will not just give you the answer. Below is some psudo code you can work off to try to find the right answer. Good Luck!

currentChar = myString.charAt(0);
i = 0;
print current character //as per comments, cover the base case
while(string has more characters)
    if current character != next character
       print next character
    i++
Sh4d0wsPlyr
  • 948
  • 12
  • 28
  • I like your no-code approach but there is one problem with "print next character". How will this solution work for string like `abc` because it looks like only `b` and `c` will be printed. – Pshemo Jan 11 '16 at 19:37
  • Ah - well stated. I'll update with that in mind. – Sh4d0wsPlyr Jan 11 '16 at 20:23
0

Use regular expression to replace all repeating characters with a single character:

"SSSAAADDDCCC".replaceAll("(.)\\1+", "$1")   // returns "SADC"

(.) matches and captures a character.
\\1+ matches one or more instances of the captured character.
$1 replaces the entire matched value with the captured character.

Non-repeating characters are not matched, and are therefore left alone.

Andreas
  • 154,647
  • 11
  • 152
  • 247
0

If you don't like the charAt method you could use substrings like this:

int j=0;
String in="sssdddaaaccc";
String out="";
for(int i=0;i<4;i++)
{
    out=out+in.subString(j,j+1);
    for(j=j; j<3;j++);
}
System.out.println(out);
njasi
  • 126
  • 8