Sort by number of apearances - java

for example, I am given a word and I have to sort its letters by the number of occurrences in that word, if 2 letters appear the same number of times it will be sorted by the lexicographic minimum.
For now, I have started to see how many times a letter appears in a word but from here I do not know exactly how to do it.
The problem requires me to use BufferedReader and BufferedWriter.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Map<Character, Integer> m = new HashMap<>();
String s = sc.nextLine();
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if (m.containsKey(c))
m.put(c, m.get(c) + 1);
else
m.put(c, 1);
}
for (char letter = 'a'; letter <= 'z'; ++letter)
if (m.containsKey(letter))
System.out.println(letter + ": " + m.get(letter));
}
For the moment I am posting what letters appear most often in the word, but I do not know how to sort them by the number of occurrences and in case there are two letters that appear at the same number of times with the minimum lexicographic.

I hope this is what you want
public static void main(String[] args) {
Map<Character, Integer> m = new HashMap<>();
String testString = "Instructions";
Map<Character, List<Character>> map = new HashMap<>();
for (int i = 0; i < testString.length(); i++) {
char someChar = testString.charAt(i);
if (someChar == ' ') {
continue;
}
char ch = testString.charAt(i);
List<Character> characters = map.getOrDefault(Character.toLowerCase(ch), new ArrayList<>());
characters.add(ch);
map.put(Character.toLowerCase(ch), characters);
}
List<Map.Entry<Character, List<Character>>> list = new ArrayList<>(map.entrySet());
list.sort((o1, o2) -> {
if (o1.getValue().size() == o2.getValue().size()) {
return o1.getKey() - o2.getKey();/// your lexicographic comparing
}
return o2.getValue().size() - o1.getValue().size();
});
list.forEach(entry -> entry.getValue().forEach(System.out::print));
}

To count letters in word, you can use much simpler method:
define array with 26 zeros, scan input line and increase appropriate index in this array, so if you meet 'a' (or 'A' - which is the same letter, but different symbol) - you will increase value at index 0, b - index 1, etc
during this scan you can also compute most occurred symbol, like this:
public static void main(final String[] args) throws IOException {
char maxSymbol = 0;
int maxCount = 0;
final int[] counts = new int[26]; // number of times each letter (a-z) appears in string
try (final BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
final String s = br.readLine().toLowerCase(); // calculate case-insensitive counts
for (final char c : s.toCharArray()) {
final int idx = c - 'a'; // convert form ASCII code to 0-based index
counts[idx]++;
if (counts[idx] > maxCount) {
maxSymbol = c; // we found most occurred symbol for the current moment
maxCount = counts[idx];
} else if (counts[idx] == maxCount) { // we found 2nd most occurred symbol for the current moment, need to check which one is minimal in lexicographical order
if (c < maxSymbol) {
maxSymbol = c;
}
}
}
}
if (maxSymbol > 0) {
System.out.println("Most frequent symbol " + maxSymbol + " occurred " + maxCount);
}
}
I've used buffered reader to get data from stdin, but I have no idea where to put buffered writer here, maybe to print result?

Related

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));

How to count the occurrence of each letter of the alphabet from a text file in Java?

I'm very new to Java and I'm struggling with my first assignment. The assignment is to scan in a text file (para1.txt) and to read through it and count how many times each letter appears.
(So, it should output something like a-57, b-21, c-12, etc.)
I feel like I'm very close to the answer, however, I'm having a little trouble actually counting the characters as they appear. Currently, my code prints "17" for all the letters, as there are 17 lines in the para1.txt file.
Here is my code so far:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class LetterCounter {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("src/para1.txt"));
int[] count = new int[26];
while (input.hasNextLine()) {
String answer = input.nextLine();
answer = answer.toLowerCase();
char[] characters = answer.toCharArray();
for (int i = 0; i < 26; i++) {
count[i]++;
}
}
for (int i = 0; i < 26; i++) {
StdOut.print((char) (i + 'a'));
StdOut.println(": " + count[i]);
}
}
}
I think you want to take the actual letters and maybe check if you actually have a letter(and not a blank or a number).
public class LetterCounter {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("src/para1.txt"));
int[] count = new int[26];
while (input.hasNextLine()) {
String answer = input.nextLine();
answer = answer.toLowerCase();
char[] characters = answer.toCharArray();
/// change here!
for (int i = 0; i< characters.length ; i++) {
if((characters[i] >='a') && (characters[i]<='z')) {
count[characters[i] -'a' ]++;
}
}
/// change ends.
}
for (int i = 0; i < 26; i++) {
StdOut.print((char) (i + 'a'));
StdOut.println(": " + count[i]);
}
}
}
In your loop, you just increment every index of the count Array:
for (int i = 0; i < 26; i++) {
count[i]++;
}
Instead what you can do is iterate over the characters Array, and increment the index at the char - 'a', to get the correct index:
for(char c : characters) {
count[c - 'a']++;
}
The only issue with this is that if there are any non alphabetic characters, this will throw an index out of bounds error. You may want to ensure it is in range:
int index = c - 'a';
if(index > 25 || index < 0) {
System.out.println("Invalid character");
} else {
//process like normal
}
Create a hashmap with character as key and count(Integer) as value.Hashmap stores key-value pairs,where key will be unique and
put() method is used to insert specific key and value into hashmap.
public class CharCount {
public static void main(String[] args) {
File f1 = new File("file-path");
HashMap<Character, Integer> charMap = new HashMap<Character, Integer>();
try {
Scanner in = new Scanner(f1);
while(in.hasNext()) {
String inputString = in.nextLine();
inputString = inputString.replace(" ", "");
char[] strArray = inputString.toCharArray();
for (char c : strArray) {
if (charMap.containsKey(c)) {
// If character is present in charMap, incrementing it's count by 1
charMap.put(c, charMap.get(c) + 1);
} else {
// If char is not present in charMap ,
// putting this character to charMap with 1 as it's value
charMap.put(c, 1);
}
}
}
// Printing the charMap
System.out.println(charMap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Maybe you're not supposed to know maps yet but one simple solution would be to use one.
Something like this
HashMap<Character, Integer> chars = new HashMap<>();
for(int i = 0; i < characters.length; i++){
if(chars.get(characters[i]) == null){
chars.put(characters[i], 1);
} else {
int num = chars.get(characters[i]);
chars.put(characters[i], num+1);
}
}
for(Character c : chars.keyset()){
print(c + " :" + chars.get(c));
}
Might be some syntax errors, wrote it here

Print all Digrams and their frequencies in a string

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.

Arranging word to formpalindrome

Hello i´ve been trying to form palindromes from this input:
String[] text ={"ivcci", "oyotta", "cecarar","bbb","babbbb"};
getPalindrome(text);
and i need to rearrange all words in array to produce this output
civic
-1
rececar
bbb
bbabb
the method expects to receive an array of Strings like
public static String getPalindrome(String[] text){}
"returning -1 means i.g "oyotta" in array can´t form a palíndrome
i´ve been testing this code and it works but i.g "cecarar" is not producing "racecar", as im a bit new in java i used an String intead an array of Strings, can anybody help to write this code properly please?
Thanks a lot!
public static String getPalindrome(String s) {
if (s == null)
return null;
Map<Character, Integer> letters = new HashMap<Character, Integer>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (!letters.containsKey(c))
letters.put(c, 1);
else
letters.put(c, letters.get(c) + 1);
}
char[] result = new char[s.length()];
int i = 0, j = result.length - 1;
Character middle = null;
for (Entry<Character, Integer> e : letters.entrySet()) {
int val = e.getValue();
char c = e.getKey();
if (val % 2 != 0) {
if (middle == null && s.length() % 2 != 0) {
middle = c;
val--;
} else
return "-1";
}
for (int k = 0; k < val / 2; k++) {
result[i++] = c;
result[j--] = c;
}
}
if (middle != null)
result[result.length / 2] = middle;
return new String(result);
}
In order for a set of characters to be able to produce a palindrome, only one of the letters can be repeated an odd number of times, so you can first weed that out.
Without writing actual code for you, here is the algorithm I would use:
Create a map of characters to a counter. Possible to do int[] counts = new int[26];
Go through each character in the input string, and increment the count: ++counts[Character.toLower(c)-'a'];
Then go through each character, and see if its odd if (counts[i] & 1 != 0) { if (oddIndex != -1) { return -1; } oddIndex=i; } This will return -1 if there is two or more odd counts.
Then, you can create a StringBuilder, and start with the oddIndex in the middle, if it exists.
Then go through the counts, and add count[i]/2 to the front and back of your string builder.
That'll give you a symmetric string from the original inputs.
Now, if you actually need words, then you'll have to have a dictionary of palindromes. You can actually preprocess all the palindromes to have a map of "sorted character string"=>"palindrome"
class PalindromeChecker
{
final Map<String, String> palindromes = new HashMap<String, String>();
public PalindromeChecker(Iterable<String> allPalindromes) {
for (String palindrome: allPalindromes) {
char[] chars = palindrome.getChars();
Arrays.sort(chars);
palindromes.put(String.valueOf(chars), palindromes);
}
}
public String getPalindrome(String input) {
char[] chars = input.getChars();
Arrays.sort(chars);
return palindromes.get(String.valueOf(chars));
}
}
As other users pointed out, a string can be rearranged as a palindrome only if there is at most one character that appears an odd number of times.
Once you have confirmed that a string can be converted to a palindrome, you can construct the palindrome as follows (this is just one of many methods of course):
place at the sides of the string all the pairs of characters that you can get
place at the middle of the string the single character that is left out, in case there is such a character.
Example:
public class Palindromes {
public static void main(String[] args) {
String[] text = {"ivcci", "oyotta", "cecarar","bbb","babbbb"};
for(String str : text){
evaluatePalindrome(str);
}
}
private static void evaluatePalindrome(String str){
PalindromeCandidate pc = new PalindromeCandidate(str);
if(pc.isPalindrome()){
System.out.println(pc.getPalindrome());
} else {
System.out.println("-1");
}
}
}
public class PalindromeCandidate {
private final CharacterCount characterCount;
public PalindromeCandidate(String originalString) {
this.characterCount = new CharacterCount(originalString);
}
public boolean isPalindrome(){
Collection<Integer> counts = characterCount.asMap().values();
int oddCountOccurrences = 0;
for(Integer count : counts){
oddCountOccurrences += (count%2);
}
return (oddCountOccurrences <= 1);
}
public String getPalindrome(){
if(!isPalindrome()){
throw new RuntimeException("Cannot be rearranged as a palindrome.");
}
Map<Character, Integer> counts = characterCount.asMap();
StringBuilder leftSide = new StringBuilder();
StringBuilder middle = new StringBuilder();
for(Character ch : counts.keySet()){
int occurrences = counts.get(ch);
while(occurrences > 1){
leftSide.append(ch);
occurrences -= 2;
}
if(occurrences > 0){
middle.append(ch);
}
}
StringBuilder rightSide = new StringBuilder(leftSide).reverse();
return leftSide.append(middle).append(rightSide).toString();
}
}
/**
* Thin wrapper around a Map<Character, Integer>. Used for counting occurences
* of characters.
*/
public class CharacterCount {
private final Map<Character, Integer> map;
public CharacterCount(String str) {
this.map = new HashMap<>();
for(Character ch : str.toCharArray()){
increment(ch);
}
}
private void increment(Character ch){
this.map.put(ch, getCount(ch) + 1);
}
private Integer getCount(Character ch){
if(map.containsKey(ch)){
return map.get(ch);
} else {
return 0;
}
}
public Map<Character, Integer> asMap(){
return new HashMap<>(map);
}
}

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