Answers for "String Frequency of Characters"

2

frequency of characters

The number of times a character is repeated in a string is known as letter(character) frequency.
Posted by: Guest on August-29-2021
0

String Frequency of Characters

String -- Frequency of Characters
Write a return method that can find the frequency of characters
Ex:  FrequencyOfChars("AAABBCDD") ==> A3B2C1D2

USING CORE JAVA
public static void main (String[] args){
sout(FrequencyOfChars(“AAABBCDD);
}
public static String FrequencyOfChars(String str) {
String nonDup = "";
for(int i=0; i < str.length(); i++){
if(!nonDup.contains(""+str.charAt(i)))
nonDup+= ""+str.charAt(i);
 
String expectedResult = "";
for( int j=0;j < nonDup.length(); j++) {
int count = 0;
for(int i=0; i < str.length(); i++) {
if(str.charAt(i) == nonDup.charAt(j))
count++;
}
expectedResult +=nonDup.charAt(j)+"" + count;
}
return expectedResult;
}

USING LINKED HASH SET
public static void main (String[] args){
sout(FrequencyOfChars(“AAABBCDD);
}

public static String FrequencyOfChars(String str) {

    String b=new LinkedHashSet<>(Arrays.asList(str.split(""))).toString();

    b = b.replace(", ","").replace("[","").replace("]","");

    String result="";

    for(int j=0; j<b.length();j++) {
        int count=0;

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

            if (str.substring(i, i + 1).equals("" + b.charAt(j))) {
                count++;
            }
        }

        result+=b.substring(j, j+1)+count;

    }

    return result;

}
Posted by: Guest on September-29-2021

Code answers related to "String Frequency of Characters"

Browse Popular Code Answers by Language