Print all Digrams and their frequencies in a string - java

I'm trying to write a program that reads a string of text and prints all digrams in this text and their frequencies. A digram is a sequence of two characters. The program prints digrams sorted based on frequencies (in descending
order).
Example of input: park car at the parking lot
Corresponding output: ar:3 pa:2 rk:2 at:1 ca:1 he:1 in:1 ki:1 lo:1 ng:1 ot:1 th:1
I have this implementation but it only works for every character in the string. How would I implement this for every digram?
import java.util.Scanner;
public class Digrams {
public static void main(String args[]) {
int ci, i, j, k, l=0;
String str, str1;
char c, ch;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a String : ");
str=scan.nextLine();
i=str.length();
for(c='A'; c<='z'; c++)
{
k=0;
for(j=0; j<i; j++)
{
ch = str.charAt(j);
if(ch == c)
{
k++;
}
}
if(k>0)
{
System.out.println("" +c +": " +k);
}
}
}
}

I know you've already got perfect answers and much much better than this, but I was wondering if I can sort the result in descending order without the help of Collections Class, it may be of help, or a new idea.
import java.util.ArrayList;
import java.util.Scanner;
public class Digrams{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Insert The Sentence");
String []sentence = in.nextLine().split(" "); // split the input according to the spaces and put them in array
//get all digrams
ArrayList<String> allDigrams = new ArrayList<String>(); // ArrayList to contain all possible digrams
for(int i=0; i<sentence.length; i++){ // do that for every word
for(int j=0; j<sentence[i].length(); j++){ // cycle through each char at each index in the sentence array
String oneDigram= "";
if(j<sentence[i].length()-1){
oneDigram += sentence[i].charAt(j); // append the char and the following char
oneDigram += sentence[i].charAt(j+1);
allDigrams.add(oneDigram); // add the one diagram to the ArrayList
}
}
}
// isolate digrams and get corresponding frequencies
ArrayList<Integer> frequency = new ArrayList<Integer>(); // for frequencies
ArrayList<String> digrams = new ArrayList<String>(); //for digrams
int freqIndex=0;
while(allDigrams.size()>0){
frequency.add(freqIndex,0);
for(int j=0; j<allDigrams.size(); j++){ // compare each UNIQUE digram with the rest of the digrams to find repetition
if(allDigrams.get(0).equalsIgnoreCase(allDigrams.get(j))){
frequency.set(freqIndex, frequency.get(freqIndex)+1); // increment frequency
}
}
String dig = allDigrams.get(0); // record the digram temporarily
while(allDigrams.contains(dig)){ // now remove all repetition from the allDigrams ArrayList
allDigrams.remove(dig);
}
digrams.add(dig); // add the UNIQUE digram
freqIndex++; // move to next index for the following digram
}
// sort result in descending order
// compare the frequency , if equal -> the first char of digram, if equal -> the second char of digram
// and move frequencies and digrams at every index in each ArrayList accordingly
for (int i = 0 ; i < frequency.size(); i++){
for (int j = 0 ; j < frequency.size() - i - 1; j++){
if (frequency.get(j) < frequency.get(j+1) ||
((frequency.get(j) == frequency.get(j+1)) && (digrams.get(j).charAt(0) > digrams.get(j+1).charAt(0))) ||
((digrams.get(j).charAt(0) == digrams.get(j+1).charAt(0)) && (digrams.get(j).charAt(1) > digrams.get(j+1).charAt(1)))){
int swap = frequency.get(j);
String swapS = digrams.get(j);
frequency.set(j, frequency.get(j+1));
frequency.set(j+1, swap);
digrams.set(j, digrams.get(j+1));
digrams.set(j+1, swapS);
}
}
}
//final result
String sortedResult="";
for(int i=0; i<frequency.size(); i++){
sortedResult+=digrams.get(i) + ":" + frequency.get(i) + " ";
}
System.out.println(sortedResult);
}
}
Input
park car at the parking lot
Output
ar:3 pa:2 rk:2 at:1 ca:1 he:1 in:1 ki:1 lo:1 ng:1 ot:1 th:1

The way to do it is to check for every 2 letter combination, and look for those instead. You can do this by using a double for-loop, like so:
public static void main(String args[]) {
int ci, i, j, k, l=0;
String str, str1, result, subString;
char c1, c2, ch;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a String : ");
str=scan.nextLine();
i=str.length();
for(c1='A'; c1<='z'; c1++)
{
for(c2='A'; c2<='z'; c2++) {
result = new String(new char[]{c1, c2});
k = 0;
for (j = 0; j < i-1; j++) {
subString = str.substring(j, j+2);
if (result.equals(subString)) {
k++;
}
}
if (k > 0) {
System.out.println("" + result + ": " + k);
}
}
}
}
This also means you have to compare Strings, rather than comparing chars. This of course means the .equals() function needs to be used, rather than the == operator, since String is an object in Java.
Result for me was:
ar: 3 at: 1 ca: 1 he: 1 in: 1 ki: 1 lo: 1 ng: 1 ot: 1 pa: 2 rk: 2 th: 1

Here's how you do it in one line:
Map<String, Long> digramFrequencies = Arrays
.stream(str
.replaceAll("(?<!^| ).(?! |$)", "$0$0") // double letters
.split(" |(?<=\\G..)")) // split into digrams
.filter(s -> s.length() > 1) // discard short terms
.collect(Collectors.groupingBy(s -> s, Collectors.counting()));
See live demo.
This works by:
doubling all letters not at start/end of words, eg "abc defg" becomes "abbc deeffg"
splitting into pairs, re-starting splits at start of word
discarding short terms (eg words like "I" and "a")
counting frequencies

This should help:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter a String : ");
String str = scan.nextLine();
ArrayList<String> repetition = new ArrayList<String>();
ArrayList<String> digrams = new ArrayList<String>();
String digram;
for(int i = 0; i < str.length() - 1; i++) {
digram = str.substring(i, i + 2);
if(repetition.contains(digram) || digram.contains(" ") || digram.length() < 2)
continue;
int occurances = (str.length() - str.replace(digram, "").length()) / 2;
occurances += (str.replaceFirst(".*?(" + digram.charAt(0) + "+).*", "$1").length() - 1) / 2;
digrams.add(digram + ":" + occurances);
repetition.add(digram);
}
Collections.sort(digrams, (s1, s2) -> s1.substring(3, 4).compareTo(s2.substring(3, 4)));
System.out.println(digrams);
}
If you don't want to use jdk8 then let me know.

Related

Arrange words according to their length [duplicate]

This question already has answers here:
How to sort String array by length using Arrays.sort()
(10 answers)
Closed 10 months ago.
INPUT: this is my string
OUTPUT: is my this string
I have to arrange words in a sentence according to their length and if two words have the same length then print them alphabetically (the first priority is length).
My incorrect code:
import java.util.Scanner;
class accordingtolength
{
void main()
{
String result="";
Scanner sc=new Scanner(System.in);
System.out.println("Enter the String");
String str=sc.nextLine();
String arr[]=str.split(" ");
int l=arr.length;
for(int i=0;i<l-1;i++)
{
String temp=arr[i]+" ";
String temp1=arr[i+1]+" ";
int a=temp.length();
int b=temp1.length();
if(a==b)
{
int c=temp.compareTo(temp1);
if(c>0)
result=temp1.concat(temp);
else
result=temp.concat(temp1);
}
else if(a>b)
result=temp1.concat(temp);
else
result=temp.concat(temp1);
}
System.out.println(result);
}
}
I know my code is incorrect so there is no need to attach the output.
Please help.
Perhaps this is what you were looking for. Using minimal external classes, this simply sorts the array of words in ascending order based on their length first and then alphabetically if those lengths are equal It uses a variant of what is known as a selection sort. It is a basic sort and quite often used as an introduction to sorting. But it is not very efficient.
read in the string and split based on spaces (I modified your regex to allow 1 or more spaces).
then use nested loops to iterate thru the list, comparing lengths.
if the word indexed by the outer loop (i) is longer than the word indexed by the inner loop (j), swap the words.
else if equal length compare words to each other and sort alphabetically (the String class implements the Comparable interface).
when both loops are finished, the array will be sorted in
then you can just iterate over the result building a string of words separated by spaces.
public class AccordingToLength {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the String:");
String str = sc.nextLine();
String arr[] = str.split("\\s+");
for (int i = 0; i < arr.length-1; i++) {
int outer = arr[i].length();
for (int j = i + 1; j < arr.length; j++) {
int inner = arr[j].length();
if (outer > inner || outer == inner && arr[i].compareTo(arr[j]) > 0) {
String temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
outer = inner; // outer has new length (what was just swapped)
}
}
}
String result = "";
for (String word : arr) {
result += word + " ";
}
System.out.println(result);
}
}
for input = "if a day now any easy when new test is done do den deed none"; this prints
a do if is any day den new now deed done easy none test when
There are multiple ways to solve this problem. The two most convenient ways are.
If you are allowed to use streams and comparator, then you can achieve it in a single line.
Arrays.stream(arr)
.sorted(Comparator
.comparing(String::length)
.thenComparing(Function.identity()))
.forEach(System.out::println);
Using Arrays.sort() to sort the actual array elements.
Arrays.sort(arr, (o1, o2) -> {
if (o1.length() > o2.length()) {
return 1;
} else if (o2.length() > o1.length()) {
return -1;
} else {
return o1.compareTo(o2);
}
});
System.out.println(Arrays.toString(arr));
If you don't want to use java provided APIs and data structures, you can implement a different version of bubble sort.
boolean isSwapped;
for (int i = 0; i < arr.length - 1; i++) {
isSwapped = false;
for (int j = 0; j < arr.length - i - 1; j++) {
if (arr[j].length() > arr[j + 1].length()
|| arr[j].length() == arr[j + 1].length() && arr[j].compareTo(arr[j + 1]) > 0) {
swap(arr, j, j + 1);
isSwapped = true;
}
}
if (!isSwapped)
break;
}

Find the occurrence of each character in a given string

"I want to find and print the occurrence of each character of given string and i have build my own logic but there is some problem.for example if i gave input as 'JAVA'.
the output that my program produce will be
J 1
A 2
V 1
A 1
Expected output :
J 1
A 2
V 1
i doesn't want to print A again. I hope you all get it what is the problem in my code."
import java.util.Scanner;
public class FindOccuranceOfCharacter {
public static void main(String[] args) {
// TODO Auto-generated method stub
String x;
Scanner input = new Scanner(System.in);
System.out.println("Enter a string");
x = input.nextLine();
x = x.toUpperCase();
int size = x.length();
for(int i =0;i<size;i++) {
int count=1;
char find = x.charAt(i);
for(int j=i+1;j<size;j++) {
if(find == x.charAt(j)) {
count++;
}
}
System.out.printf("%c\t%d",x.charAt(i),count);
System.out.println();
}
}
}
The reason your code prints the way it does is that your loop prints each character (and subsequent matches) for a given index. You really need to store the character and counts in a data structure with one loop, and then display the counts with a second. A LinkedHashMap<Character, Integer> is perfect for your use case (because it preserves key insertion order, no additional logic is needed to restore input order). Additional changes I would make include using String.toCharArray() and a for-each loop. Like,
Map<Character, Integer> map = new LinkedHashMap<>();
for (char ch : x.toUpperCase().toCharArray()) {
map.put(ch, map.getOrDefault(ch, 0) + 1);
}
for (char ch : map.keySet()) {
System.out.printf("%c\t%d%n", ch, map.get(ch));
}
Which I tested with x equal to JAVA and got (as requested)
J 1
A 2
V 1
Using hashMap it's easy to accumulate the number of occurrences and you can easily print iterating the HashMap.
This is the code:
public class FindOccuranceOfCharacter {
public static void main(String[] args) {
String x;
Scanner input = new Scanner(System.in);
System.out.println("Enter a string");
x = input.nextLine();
HashMap<Character,Integer> occurance = new HashMap<Character,Integer>();
x = x.toUpperCase();
int size = x.length();
for(int i =0;i<size;i++) {
int count=1;
char find = x.charAt(i);
occurance.put(find, occurance.getOrDefault(find, 0) + 1);
}
for (Character key : occurance.keySet()) {
Integer value = occurance.get(key);
System.out.println("Key = " + key + ", Value = " + value);
}
}
This is not an optimal solution, but I have tried to change your code as little as possible:
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a string");
// use a StringBuilder to delete chars later on
StringBuilder x = new StringBuilder(input.nextLine().toUpperCase());
for(int i=0;i<x.length();i++) {
int count=1;
char find = x.charAt(i);
// go through the rest of the string from the end so we do not mess up with the index
for(int j=x.length()-1;j>i;j--) {
if(find == x.charAt(j)) {
count++;
// delete counted occurences of the same char
x.deleteCharAt(j);
}
}
System.out.printf("%c\t%d",x.charAt(i),count);
System.out.println();
}
}
My more preferred Java stream would look like this:
input.nextLine().toUpperCase().chars()
.mapToObj(i -> (char) i)
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()))
.forEach((k, v) -> System.out.println(k + "\t" + v));

Maximum repeated String in an array

The problem is
how to get the maximum repeated String in an array using only operations on the arrays in java?
so i got into this question in a test and couldn't figure it out.
lets suppose we have an array of string.
str1[] = { "abbey", "bob", "caley", "caley", "zeeman", "abbey", "bob", "abbey" }
str2[] = { "abbey", "bob", "caley", "caley", "zeeman", "abbey", "bob", "abbey", "caley" }
in str1 abbey was maximum repeated, so abbey should be returned and
in str2 abbey and caley both have same number of repetitions and hence we take maximum alphabet as the winner and is returned(caley here).
c > a
so i tried till
import java.util.*;
public class test {
static String highestRepeated(String[] str) {
int n = str.length, num = 0;
String temp;
String str2[] = new String[n / 2];
for (int k = 0;k < n; k++) { // outer comparision
for (int l = k + 1; l < n; l++) { // inner comparision
if (str[k].equals(str[l])) {
// if matched, increase count
num++;
}
}
// I'm stuck here
}
return result;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("enter how many votes");
int n = sc.nextInt();
String[] str = new String[n];
for (int i = 0; i < n; i++) {
Str[i] = sc.nextLine();
}
String res = highestRepeated(str);
System.out.println(res + " is the winner");
}
}
so, how should i take the count of occurrence of each string with and attach it with the string itself.
All this, without using a map and any hashing but just by using arrays?
Here is a (unpolished) solution:
static String highestRepeated(String[] str) {
String[] sorted = Arrays.copyOf(str, str.length);
Arrays.sort(sorted, 0, sorted.length, Comparator.reverseOrder());
String currentString = sorted[0];
String bestString = sorted[0];
int maxCount = 1;
int currentCount = 1;
for (int i = 1 ; i < sorted.length ; i++) {
if (currentString.equals(sorted[i])) {
currentCount++;
} else {
if (maxCount < currentCount) {
maxCount = currentCount;
bestString = currentString;
}
currentString = sorted[i];
currentCount = 1;
}
}
if (currentCount > maxCount) {
return currentString;
}
return bestString;
}
Explanation:
Sort the array from highest to lowest lexicographically. That's what Arrays.sort(sorted, 0, sorted.length, Comparator.reverseOrder()); does. we sort in this order because you want the largest string if there are multiple strings with the same number of repeats.
Now we can just count the strings by looping through the array. We don't need a hash map or anything because we know that there will be no more of a string in the rest of the array when we encounter a different string.
currentString is the string that we are currently counting the number of repeats of, using currentCount. maxCount is the number of occurrence of the most repeated string - bestString - that we have currently counted.
The if statement is pretty self-explanatory: if it is the same string, count it, otherwise see if the previous string we counted (currentCount) appears more times than the current max.
At the end, I check if the last string being counted is more than max. If the last string in the array happens to be the most repeated one, bestString won't be assigned to it because bestString is only assigned when a different string is encountered.
Note that this algorithm does not handle edge cases like empty arrays or only one element arrays. I'm sure you will figure that out yourself.
another version
static String lastMostFrequent(String ... strs) {
if (strs.length == 0) return null;
Arrays.sort(strs);
String str = strs[0];
for (int longest=0, l=1, i=1; i<strs.length; i++) {
if (!strs[i-1].equals(strs[i])) { l=1; continue; }
if (++l < longest) continue;
longest = l;
str = strs[i];
}
return str;
}
change in
if (++l <= longest) continue;
for firstMostFrequent
you can't use == to check if two strings are the same.
try using this instead:
if (str[k].equals(str[l])) {
// if matched, increase count
num++;
}

How do I count the number of occurrences of a char in a Multiple String?

My question is so special ,
giving those Strings
123456
String1 ABCD
String2 BDD
String3 CDEF
As we can see
the number of A in column 1 is 1.
the number of B in column 2 is 2.
the number of C in column 3 is 2.
the number of D in column 3 is 1.
the number of D in column 4 is 3.
the number of E in column 5 is 1.
the number of F in column 6 is 1.
the purpose of those calculs is to get the char that appear the most in each Column.
what is the best DataStructure i can use to handle this issue? knowing that i know the lenght of each String only at the Execution time.
the information i know already is the n° of column where each String begin.
the idea i have and i think it's not the best is iterating over the column n° and couting how much each char appear and finally finding that most occurred char.
Do you have some better solution?
info: My string could contain only those char[A,B,C,D,E,F]
Thank you.
Go through this sample code which you can insert Strings as list so there won't be any restrictions on number of String in the code but correct output will be given. I have added inline comments where it's required.
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class StringOperation {
public static void main(String[] args) {
List<String> stringList=new ArrayList<String>();
stringList.add("ABCD");
stringList.add(" BDD");
stringList.add(" CDEF");
stringList.add("ABCD");
char[][] array=getTwoDimentionArray(stringList);
for (int i = 0; i < array.length; i++) {
char[] cs = array[i];
numberOfCharactorsinString(cs, i);
}
}
//This method will create two dimension array from String list same time it will convert columns in to rows
public static char[][] getTwoDimentionArray(List<String> list){
char[][] twoDimenArray=null;
int maxLength=0;
for (String strings : list) {
if(maxLength<strings.length()){
maxLength=strings.length();
}
}
twoDimenArray=new char[maxLength][list.size()];
for (int i = 0; i < list.size(); i++) {
char[] charArray=list.get(i).toCharArray();
for (int j = 0; j < charArray.length; j++) {
twoDimenArray[j][i] = charArray[j];
}
}
return twoDimenArray;
}
//This method will return the char occurrences in the given char array
public static void numberOfCharactorsinString(char[] charArray,int count){
//Here we use set to identify unique chars in the char array
Set<Character> uniqueSet=new HashSet<Character>();
int forcount=0;
for (Character charVar : charArray) {
int occurent=1;
//check whether the searching char is not empty and not a space and not in previously counted
if( charVar!=Character.MIN_VALUE && charVar!=' ' && !uniqueSet.contains(charVar) && forcount<charArray.length){
uniqueSet.add(charVar);
for (int x=forcount+1;x<charArray.length;x++ ) {
if(charArray[x]==charVar){
occurent++;
}
}
System.out.println("The number of "+charVar+" in column "+(count+1)+" is "+occurent+".");
}
forcount++;
}
}
}
If you provide input as (Note that I have added additional input in here in 4th line)
String1 ABCD
String2 BDD
String3 CDEF
String1 ABCD
The out put will be as bellow
The number of A in column 1 is 2.
The number of B in column 2 is 3.
The number of C in column 3 is 3.
The number of D in column 3 is 1.
The number of D in column 4 is 4.
The number of E in column 5 is 1.
The number of F in column 6 is 1.
public class Main {
public static void main(String[] args) {
String str1 = "ABCD ";
String str2 = " BDD ";
String str3 = " CDEF";
String[] reversed = getReversed(str1, str2, str3); // reverse rows with columns
for(int i=0; i< reversed.length; i++){
String trimedString = reversed[i].trim(); // removes spaces that around the string
System.out.println(findMaxOccurrenceCharValue(trimedString)); // counts the maximum occurrence char
}
}
private static String[] getReversed(String str1, String str2, String str3){
char[] s1 = str1.toCharArray();
char[] s2 = str2.toCharArray();
char[] s3 = str3.toCharArray();
String[] newStr = new String[6];
for(int i =0; i<6; i++){
newStr[i] = "" + s1[i] + s2[i] + s3[i];
}
return newStr;
}
private static String findMaxOccurrenceCharValue(String str) {
char[] array = str.toCharArray();
int[] count = new int[1000];
for(char c: array){
count[c]++;
}
// find the max occurrence character and number of occurrence
String maxCharacter = "";
int maxValue = -1;
for(int i=0;i< array.length;i++){
if(count[array[i]] > maxValue){
maxValue = count[array[i]];
maxCharacter = String.valueOf(array[i]);
}
}
return maxCharacter + "=" + maxValue;
}
}
Output:
A=1
B=2
C=2
D=3
E=1
F=1

count specific characters in a string (Java)

I have a homework assignment to count specific chars in string.
For example: string = "America"
The output should be = a appear 2 times, m appear 1 time, e appear 1 time, r appear 1 time, i appear 1 time and c appear 1 time
public class switchbobo {
/**
* #param args
*/ // TODO Auto-generated method stub
public static void main(String[] args){
String s = "BUNANA";
String lower = s.toLowerCase();
char[] c = lower.toCharArray(); // converting to a char array
int freq =0, freq2 = 0,freq3 = 0,freq4=0,freq5 = 0;
for(int i = 0; i< c.length;i++) {
if(c[i]=='a') // looking for 'a' only
freq++;
if(c[i]=='b')
freq2++;
if (c[i]=='c') {
freq3++;
}
if (c[i]=='d') {
freq4++;
}
}
System.out.println("Total chars "+c.length);
if (freq > 0) {
System.out.println("Number of 'a' are "+freq);
}
}
}
code above is what I have done, but I think it is not make sense to have 26 variables (one for each letter). Do you guys have alternative result?
Obviously your intuition of having a variable for each letter is correct.
The problem is that you don't have any automated way to do the same work on different variables, you don't have any trivial syntax which helps you doing the same work (counting a single char frequency) for 26 different variables.
So what could you do? I'll hint you toward two solutions:
you can use an array (but you will have to find a way to map character a-z to indices 0-25, which is somehow trivial is you reason about ASCII encoding)
you can use a HashMap<Character, Integer> which is an associative container that, in this situation, allows you to have numbers mapped to specific characters so it perfectly fits your needs
You can use HashMap of Character key and Integer value.
HashMap<Character,Integer>
iterate through the string
-if the character exists in the map get the Integer value and increment it.
-if not then insert it to map and set the integer value for 0
This is a pseudo code and you have to try coding it
I am using a HashMap for the solution.
import java.util.*;
public class Sample2 {
/**
* #param args
*/
public static void main(String[] args)
{
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
String test = "BUNANA";
char[] chars = test.toCharArray();
for(int i=0; i<chars.length;i++)
{
if(!map.containsKey(chars[i]))
{
map.put(chars[i], 1);
}
map.put(chars[i], map.get(chars[i])+1);
}
System.out.println(map.toString());
}
}
Produced Output -
{U=2, A=3, B=2, N=3}
In continuation to Jack's answer the following code could be your solution. It uses the an array to store the frequency of characters.
public class SwitchBobo
{
public static void main(String[] args)
{
String s = "BUNANA";
String lower = s.toLowerCase();
char[] c = lower.toCharArray();
int[] freq = new int[26];
for(int i = 0; i< c.length;i++)
{
if(c[i] <= 122)
{
if(c[i] >= 97)
{
freq[(c[i]-97)]++;
}
}
}
System.out.println("Total chars " + c.length);
for(int i = 0; i < 26; i++)
{
if(freq[i] != 0)
System.out.println(((char)(i+97)) + "\t" + freq[i]);
}
}
}
It will give the following output:
Total chars 6
a 2
b 1
n 2
u 1
int a[]=new int[26];//default with count as 0
for each chars at string
if (String having uppercase)
a[chars-'A' ]++
if lowercase
then a[chars-'a']++
public class TestCharCount {
public static void main(String args[]) {
String s = "america";
int len = s.length();
char[] c = s.toCharArray();
int ct = 0;
for (int i = 0; i < len; i++) {
ct = 1;
for (int j = i + 1; j < len; j++) {
if (c[i] == ' ')
break;
if (c[i] == c[j]) {
ct++;
c[j] = ' ';
}
}
if (c[i] != ' ')
System.out.println("number of occurance(s) of " + c[i] + ":"
+ ct);
}
}
}
maybe you can use this
public static int CountInstanceOfChar(String text, char character ) {
char[] listOfChars = text.toCharArray();
int total = 0 ;
for(int charIndex = 0 ; charIndex < listOfChars.length ; charIndex++)
if(listOfChars[charIndex] == character)
total++;
return total;
}
for example:
String text = "america";
char charToFind = 'a';
System.out.println(charToFind +" appear " + CountInstanceOfChar(text,charToFind) +" times");
Count char 'l' in the string.
String test = "Hello";
int count=0;
for(int i=0;i<test.length();i++){
if(test.charAt(i)== 'l'){
count++;
}
}
or
int count= StringUtils.countMatches("Hello", "l");

Categories

Resources