user647207
user647207

Reputation: 177

how can i calculate the number of specific chars in a string?

Given a string how can i figure out the number of times each char in a string repeats itself ex: aaaabbaaDD output: 4a2b2a2D

public static void Calc() {

        Input();

        int count = 1;

        String compressed = "";

        for (int i = 0; i < input.length(); i++) {

            if (lastChar == input.charAt(i)) {

                count++;

                compressed += Integer.toString(count) + input.charAt(i);
            }

            else {

                lastChar = input.charAt(i);
                count = 1;
            }

        }

        System.out.println(compressed);

    }

Upvotes: 0

Views: 1557

Answers (4)

Lavanya Mohan
Lavanya Mohan

Reputation: 1516

This program first finds the unique characters or numbers in a string. It will then check the frequency of occurance. This program considers capital and small case as different characters. You can modify it if required by using ignorecase method.


import java.io.*;
public class RunLength {
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    public static void main(String[] args) throws IOException {
        System.out.println("Please enter the string");
        String str = br.readLine();//the input string is in str
        calculateFrequency(str);
    }
    private static void calculateFrequency(String str) {
        int length = str.length();
        String characters[] = new String[length];//to store all unique characters in string
        int frequency[] = new int[length];//to store the frequency of the characters
        for (int i = 0; i < length; i++) {
            characters[i] = null;
            frequency[i] = 0;
        }

//To get unique characters char temp; String temporary; int uniqueCount = 0; for (int i = 0; i < length; i++) { int flag = 0; temp = str.charAt(i); temporary = "" + temp; for (int j = 0; j < length; j++) { if (characters[j] != null && characters[j].equals(temporary)) { flag = 1; break; } } if (flag == 0) { characters[uniqueCount] = temporary; uniqueCount++; } } // To get the frequency of the characters for(int i=0;i<length;i++){ temp=str.charAt(i); temporary = ""+temp; for(int j=0;i<characters.length;j++){ if(characters[j].equals(temporary)){ frequency[j]++; break; } } } // To display the output for (int i = 0; i < length; i++) { if (characters[i] != null) { System.out.println(characters[i]+" "+frequency[i]); } } }}

Upvotes: 1

Johnbabu Koppolu
Johnbabu Koppolu

Reputation: 3252

@Balarmurugan k's solution is better - but just by improving upon your code I came up with this -

    String input = "aaaabbaaDD";
    int count = 0;
    char lastChar = 0;
    int inputSize = input.length();
    String output = "";
    for (int i = 0; i < inputSize; i++) {
        if (i == 0) {
            lastChar = input.charAt(i);
            count++;
        } else {
            if (lastChar == input.charAt(i)) {
                count++;
            } else {
                output = output + count + "" + lastChar;
                count = 1;
                lastChar = input.charAt(i);
            }
        }
    }
    output = output + count + "" + lastChar;
    System.out.println(output);

Upvotes: 0

Bala
Bala

Reputation: 4547

What you'r looking for is "Run-length encoding". Here is the working code to do that;

 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 public class RunLengthEncoding {

public static String encode(String source) {
    StringBuffer dest = new StringBuffer();
   //  iterate through input string 
   // Iterate the string N no.of.times where N is size of the string to find run length for each character
    for (int i = 0; i < source.length(); i++) {
        // By default run Length for all character is one
        int runLength = 1;

        // Loop condition will break when it finds next character is different from previous character. 
        while (i+1 < source.length() && source.charAt(i) == source.charAt(i+1)) {
            runLength++;
            i++;
        }
        dest.append(runLength);
        dest.append(source.charAt(i));
    }
    return dest.toString();
}

public static String decode(String source) {
    StringBuffer dest = new StringBuffer();
    Pattern pattern = Pattern.compile("[0-9]+|[a-zA-Z]");
    Matcher matcher = pattern.matcher(source);
    while (matcher.find()) {
        int number = Integer.parseInt(matcher.group());
        matcher.find();
        while (number-- != 0) {
            dest.append(matcher.group());
        }
    }
    return dest.toString();
}

public static void main(String[] args) {
    String example = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";
    System.out.println(encode(example));
    System.out.println(decode("1W1B1W1B1W1B1W1B1W1B1W1B1W1B"));
}
 }

Upvotes: 1

Thilo
Thilo

Reputation: 262534

Some hints: In your code sample you also need to reset count to 0 when the run ends (when you update lastChar). And you need to output the final run (after the loop is done). And you need some kind of else or continue between the two cases.

Upvotes: 0

Related Questions