Misr
Misr

Reputation: 53

Count the number of times a character appears in a contiguous manner in a string

I'm new to Java. I'm trying to print the characters present in the string along with their count. The count only increments when the same character is present next to it.

Ex:

I/O : Sssgs

O/P : S1s2g1s1

Counting the occurence of each character gives the count of the full count regardless of the characters not being present next to each other. Tampering with the i & j loops gives an OutOfBounds error.

      //ch[] is the String converted to a character array.
     //count[] is an array to store count of the characters      

    //Checks if present char and next char are same and increments count
    for(int i=0;i<ch.length;i++)    
    {
        count[i]=0;
        for(int j=0;j<ch.length;j++)
        {
            if(ch[i]==ch[j])
            {
                count[i]++;
            }
        }
    }

    //Prints Distinct char
    for(int i=0;i<ch.length;i++)
    {
        int j;
        for(j=0;j<i;j++)
        {
            if(ch[i]==ch[j])
            {
                break;
            }
        }

        if(i==j)
        {
            System.out.print(ch[i]+" "+count[i]);
        }
    }

The Input is > HelloWorld

The expected output should be > H1 e1 l2 o1 W1 o1 r1 l1 d1

Upvotes: 4

Views: 866

Answers (4)

Joakim Danielson
Joakim Danielson

Reputation: 51983

Here is a simpe solution that doesn't use any extra array and instead directly prints the counted char when the next one is different

char prevChar = ch[0];
int count = 1;
for (int i = 1; i < ch.length; i++) {
  if (ch[i] != prevChar) {
    System.out.printf("%c%d ", prevChar, count);
    count = 1;
    prevChar = ch[i];
  } else {
    count++;
  }
}
System.out.printf("%c%d ", prevChar, count); 

Upvotes: 1

user2087103
user2087103

Reputation: 161

I hate this solution, but I guess you are using a char[] because of needs. If not compulsory, i would recommend you to use a StringBuilder as Lino suggested.

char blankChar = " ".charAt(0);
if (stringInput == null || "".equals(stringInput)) {
    System.out.println("Empty input");
}
char[] ch = stringInput.toCharArray();
char lastChar = ch[0];
int numAppearanceslastChar = 0;
for (char element : ch) {
    if (element == blankChar) {
        continue;
    }
    if (lastChar == element) {
        numAppearanceslastChar++;
    } else {
        System.out.print(lastChar+""+numAppearanceslastChar+" ");
        lastChar = element;
        numAppearanceslastChar = 1;
    }
}
System.out.println(lastChar+""+numAppearanceslastChar+" ");

Output: H1 e1 l2 o1 w1 o1 r1 l1 d1

Explanation: Read the whole word only once (note you wuere doing 3 times a for loop) and compare last read char with the new one. If they match, increment the number of occurences of that char. If they are not, then you print them and set the new characted as the last read. When you end reading the word, print the last char read.

Always remember to keep it simple! And sanitize (you would get a nullPointer in this code if receiving a null or empty, just wrote it there to point it out).

Upvotes: 0

Lino
Lino

Reputation: 19926

I came up with this:

public static String count(String in) {
    if (in == null || in.isEmpty()) {
        return in;
    }
    int length = in.length();
    if (length == 1) {
        return in + '1';
    }
    StringBuilder out = new StringBuilder(length << 1);

    char previous = in.charAt(0);
    int count = 1;
    for (int i = 1; i < length; i++) {
        char current = in.charAt(i);
        if (previous == current) {
            count++;
        } else {
            out.append(previous).append(count);
            previous = current;
            count = 1;
        }
    }
    return out.append(previous).append(count).toString();
}

Takes care of null and empty strings. And strings with length == 1 (which is just string + 1).

This solution also doesn't need to create an additional char[] array, as it is working with charAt

Upvotes: 0

Rafał Sokalski
Rafał Sokalski

Reputation: 2007

I just made some corrections in your code and below it is how it looks like:

public static void main(String[] args) {
    String s = "Sssgs";
    char[] ch = s.toCharArray();
    int[] count = new int[20];

       for(int i=0;i<ch.length;i++)    
        {
            count[i]=0;
            for(int j=i;j<ch.length;j++)
            {
                if(ch[i]==ch[j])
                {
                    count[i]++;
                } else {
                    break;
                }
            }
        }

        //Prints Distinct char
        for(int i=0;i<ch.length;i += count[i])
        {
            System.out.print(ch[i] + "" +count[i]);
        }
}

Most changes was in Prints Distincts when I just read character and it number of occurence and then jump that number in iteration. It lets me stops on the next character which is different

The output for "Sssgs" is "S1s2g1s1" and for "HelloWorld" is "H1e1l2o1W1o1r1l1d1"

Upvotes: 1

Related Questions