Calculate the frequency of each character in a given string
import java.io.IOException;
/**
*
* @author Sunshine
*/
public class Ques2 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
String str = "hello kiran";
int count = 0;
String temp = "";
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i); // take one character (c) in string
for (int j = i; j < str.length(); j++) {
char k = str.charAt(j);
// take one character (c) and compare with each character (k) in the string
// also check that character (c) is not already counted.
// if condition passes then increment the count.
if (c == k && temp.indexOf(c) == -1) {
count = count + 1;
}
}
if (temp.indexOf(c) == -1) // if it is not already counted
{
temp = temp + c; // append the character to the temp indicating
// that you have already counted it.
System.out.println("Character " + c + " occurs " + count + " times");
}
// reset the counter for next iteration
count = 0;
}
}
eg teddy d= 2 e=1 t=1 y=1
/**
*
* @author Sunshine
*/
public class Ques2 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
String str = "hello kiran";
int count = 0;
String temp = "";
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i); // take one character (c) in string
for (int j = i; j < str.length(); j++) {
char k = str.charAt(j);
// take one character (c) and compare with each character (k) in the string
// also check that character (c) is not already counted.
// if condition passes then increment the count.
if (c == k && temp.indexOf(c) == -1) {
count = count + 1;
}
}
if (temp.indexOf(c) == -1) // if it is not already counted
{
temp = temp + c; // append the character to the temp indicating
// that you have already counted it.
System.out.println("Character " + c + " occurs " + count + " times");
}
// reset the counter for next iteration
count = 0;
}
}
}
No comments:
Post a Comment