Java built-in method - occurrences of a char in a string - java

Is there a java built-in method to count occurrences of a char in a string ?
for example:
s= "Hello My name is Joel"
the number of occurrences of l is 3
Thanks

There is no such method, but you can do:
String s = "Hello My name is Joel";
int counter = 0;
for( int i=0; i<s.length(); i++ ) {
if( s.charAt(i) == 'l' ) {
counter++;
}
}
(code from Simple way to count character occurrences in a string)

If you want to count the number of times multiple characters have appeared in a particular string, then mapping of characters with their number of occurrences in the string will be a good option. Here's how one would achieve the solution in that case:
import java.util.HashMap;
import java.util.Map;
public class CharacterMapper
{
private Map<Character, Integer> charCountMap;
public CharacterMapper(String s)
{
initializeCharCountMap(s);
}
private void initializeCharCountMap(String s)
{
charCountMap = new HashMap<>();
for (int i = 0; i < s.length(); i++)
{
char ch = s.charAt(i);
if (!charCountMap.containsKey(ch))
{
charCountMap.put(ch, 1);
}
else
{
charCountMap.put(ch, charCountMap.get(ch) + 1);
}
}
}
public int getCountOf(char ch)
{
if (charCountMap.containsKey(ch))
return charCountMap.get(ch);
return 0;
}
public static void main(String[] args)
{
CharacterMapper ob = new CharacterMapper("Hello My name is Joel");
System.out.println(ob.getCountOf('o')); // Prints 2
}
}

Related

Count of of characters matched in sequence of two string

I want to match two string and get how many chars matched in sequence.
Like :
String one="ABCDEFGHIJK";
String two="ZANDEFGHOPQ";
like you can see that it must return 5 chars in sequence matched because DEFGH are exist on both sequence.
Thanks
import java.io.*;
import java.util.*;
class happy {
public static void main(String args[])
{
String one="ABCDEFGHIJK";
String two="ZANDEFGHOPQ";
int a=0,c=0;
if(one.length()<two.length())
a=one.length();
else
a=two.length();
for(int i=0;i<a;i++)
{
if(one.charAt(i)==(two.charAt(i)))
c++;
}
System.out.println(c);
}
}
public class Test {
public static void main(String[] args) {
String one="ABCDEFGHIJK";
String two="ZANDEFGHOPQ";
int size1 = one.length();
int size2 = two.length();
int i = 0;
int j = (size1 >= size2 ? size2 : size1);
char[] oneTab = one.toCharArray();
char[] twoTab = two.toCharArray();
int k = 0;
for(i = 0; i< j; i++){
if((String.valueOf(oneTab[i])).equals(String.valueOf(twoTab[i]))){
k = k+1;
};
};
System.out.println(k);
}
}
try this
String one="ABCDEFGHIJK";
String two="ZANDEFGHOPQ";
int cnt=0;
for (int i=0;i<one.length();i++){
for (int j=0;j<two.length();j++){
if(one.charAt(i) == two.charAt(j) ){
cnt++;
}
}
}
Toast.makeText(this, "count"+cnt, Toast.LENGTH_SHORT).show();
Maybe something like this will do it.
String one="ABCDEFGHIJK";
String two="ZANDEFGHOPQ";
int counter = 0;
// Iterate over the string character by character - stop when reaching the
// end of the shortest string
for( int i=0; i<one.length() && i<two.length(); i++ ) {
// Compare the strings character at the current position/index
if(one.charAt(i) == two.charAt(i)) {
// The characters matched so increment the counter
counter++;
}
}

How to get individual letters in a string

I am so confused on how to search individual letters (specific vowels) within the the array of my string.
import static java.lang.System.*;
import java.util.Arrays;
public class Word {
private String word;
private static String vowels = "AEIOUaeiou"; //only one
public Word() {
String vow = "";
vowels = vow;
}
public Word(String wrd) {
word=wrd;
}
public void setWord(String wrd) {
}
public int getNumVowels(String[] ray, String vowels) {
int count=0;
for(String item : ray) {
if() {
count = count + 1;
}
}
return count;
}
public int getLength(String[] ray) {
return 0;
}
public String toString(String[] ray) {
return "";
}
}
This is the runner. How do I getNumVowels to work by searching for an individual letter by the input?
import java.util.Arrays;
import java.util.Scanner;
import static java.lang.System.*;
public class WordRunner {
public static void main(String[] args) {
String alpha="";
String [] ray = new String[4];
ray[0] ="Polo";
ray[1] ="Crazy";
ray[2] ="Abracadabra";
ray[3] ="Awesome";
out.println(Arrays.toString(ray));
out.println("Number of vowels: " + Arrays.getNumVowels(ray));
out.println("Length of the word: " + Arrays.getLength(ray));
}
}
There are several errors in your code...
You're calling Arrays methods which does not exists...
out.println("Number of vowels: "+ Arrays.getNumVowels(ray));
out.println("Length of the word: "+ Arrays.getLength(ray));
Modify Word class (you put a lot of innecessary stuff):
import static java.lang.System.*;
import java.util.Arrays;
public class Word
{
private static String vowels = "AEIOUaeiou"; //only one
public static int getNumVowels(String word)
{
int count=0;
for (int i=0; i < word.length(); i++)
{
// check if selected char is a vowel
if (vowels.contains(word.charAt(i) + ""))
{
count ++; // same as count = count + 1
}
}
return count;
}
}
Then to call the method, as it is static:
public static void main(String[] args)
{
System.out.println("Number of vowels of Polo: "+ Word.getNumVowels("Polo"));
//Output:
// Number of vowels of Polo: 2
// or execute like this:
String a = "Polo";
int vowels = Word.getNumVowels(a);
System.out.printlm("Number of vowels of Polo: "+ vowels);
//Output:
// Number of vowels of Polo: 2
}
UPDATE: if you want your word class count vowels in an array, simply use already existing method.
Inside Word class add an overload of the existing method that receives an array and use the old one:
// overload: same method name, but different arguments!!!
public static int getNumVowels(String[] array)
{
int count = 0;
for (i = 0; i < array.lenght; i ++){
// use existing method to save code!!
count += getNumVowels(array[i]);
}
return count;
}
And use it like:
String [] ray = new String[4];
ray[0] ="Polo";
ray[1] ="Crazy";
ray[2] ="Abracadabra";
ray[3] ="Awesome";
int vowels = Word.getNumVowels(ray); // count vowels in ALL array words...
You can get the char array from the string and loop over it looking for the required vowel (if you want to count how many times a single vowel appears, then there's no need to pass a string, you can simply use a char).
public int getNumVowels(String[] ray, char vowel) {
int count=0;
for(String s: ray)
{
char[] array = s.toLowerCase().toCharArray();
for (int i=0; i<array.length; i++) {
if(array[i] == vowel) {
count = count + 1;
}
}
}
return count;
}
You need the s.toLowerCase() only if you want the search to be case insensitive (because for example 'a' is different from 'A').
Straightforward way:
String vowels = "AEIOUaeiou";
int count = 0;
for (int i=0; i<str.length(); i++)
{
if (vowels.contains(str.charAt(i) + ""))
{
count++;
}
}
return count;

How to find the most frequently occurring character in a string with Java?

Given a paragraph as input, find the most frequently occurring character. Note that the case of the character does not matter. If more than one character has the same maximum occurring frequency, return all of them
I was trying this question but I ended up with nothing. Following is the code that I tried but it has many errors I am unable to correct:
public class MaximumOccuringChar {
static String testcase1 = "Hello! Are you all fine? What are u doing today? Hey Guyz,Listen! I have a plan for today.";
public static void main(String[] args)
{
MaximumOccuringChar test = new MaximumOccuringChar();
char[] result = test.maximumOccuringChar(testcase1);
System.out.println(result);
}
public char[] maximumOccuringChar(String str)
{
int temp = 0;
int count = 0;
int current = 0;
char[] maxchar = new char[str.length()];
for (int i = 0; i < str.length(); i++)
{
char ch = str.charAt(i);
for (int j = i + 1; j < str.length(); j++)
{
char ch1 = str.charAt(j);
if (ch != ch1)
{
count++;
}
}
if (count > temp)
{
temp = count;
maxchar[current] = ch;
current++;
}
}
return maxchar;
}
}
You already got your answer here: https://stackoverflow.com/a/21749133/1661864
It's a most easy way I can imagine.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MaximumOccurringChar {
static final String TEST_CASE_1 = "Hello! Are you all fine? What are u doing today? Hey Guyz,Listen! I have a plan for today. Help!";
public static void main(String[] args) {
MaximumOccurringChar test = new MaximumOccurringChar();
List<Character> result = test.maximumOccurringChars(TEST_CASE_1, true);
System.out.println(result);
}
public List<Character> maximumOccurringChars(String str) {
return maximumOccurringChars(str, false);
}
// set skipSpaces true if you want to skip spaces
public List<Character> maximumOccurringChars(String str, Boolean skipSpaces) {
Map<Character, Integer> map = new HashMap<>();
List<Character> occurrences = new ArrayList<>();
int maxOccurring = 0;
// creates map of all characters
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (skipSpaces && ch == ' ') // skips spaces if needed
continue;
if (map.containsKey(ch)) {
map.put(ch, map.get(ch) + 1);
} else {
map.put(ch, 1);
}
if (map.get(ch) > maxOccurring) {
maxOccurring = map.get(ch); // saves max occurring
}
}
// finds all characters with maxOccurring and adds it to occurrences List
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
if (entry.getValue() == maxOccurring) {
occurrences.add(entry.getKey());
}
}
return occurrences;
}
}
Why don't you simply use N letter buckets (N=number of letters in alphabet) ? Just go along the string and increment the corresponding letter bucket. Time complexity O(n), space complexity O(N)
This method allows you to find the most frequently occurring character in a string:
public char maximumOccuringChar(String str) {
return str.chars()
.mapToObj(x -> (char) x) // box to Character
.collect(groupingBy(x -> x, counting())) // collect to Map<Character, Long>
.entrySet().stream()
.max(comparingByValue()) // find entry with largest count
.get() // or throw if source string is empty
.getKey();
}
import java.util.Scanner;
public class MaximumOccurringChar{
static String testcase1 = "Hello! Are you all fine? What are u doing today? Hey Guyz,Listen! I have a plan for today.";
public static void main(String[] args) {
MaximumOccurringChar test = new MaximumOccurringChar();
String result = test.maximumOccuringChar(testcase1);
System.out.println(result);
}
public String maximumOccuringChar(String str) {
int temp = 0;
int count = 0;
int current = 0;
int ind = 0;
char[] arrayChar = {'a','b' , 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
int[] numChar = new int[26];
char ch;
String s="";
str = str.toLowerCase();
for (int i = 0; i < 26; i++) {
count = 0;
for (int j = 0; j < str.length(); j++) {
ch = str.charAt(j);
if (arrayChar[i] == ch) {
count++;
}
}
numChar[i] = count++;
}
temp = numChar[0];
for (int i = 1; i < numChar.length; i++) {
if (temp < numChar[i]) {
temp = numChar[i];
ind = i;
break;
}
}
System.out.println(numChar.toString());
for(int c=0;c<26;c++)
{
if(numChar[c]==temp)
s+=arrayChar[c]+" ";
}
return s;
}
}
Algorithm:-
Copying the String character by character to LinkedHashMap.
If its a new character then insert new character , 1.
If character is already present in the LinkedHashMap then update the value by incrementing by 1.
Iterating over the entry one by one and storing it in a Entry object.
If value of key stored in entry object is greater than or equal to current entry then do nothing
Else, store new entry in the Entry object
After looping through, simply print the key and value from Entry object.
public class Characterop {
public void maxOccur(String ip)
{
LinkedHashMap<Character, Integer> hash = new LinkedHashMap();
for(int i = 0; i<ip.length();i++)
{
char ch = ip.charAt(i);
if(hash.containsKey(ch))
{
hash.put(ch, (hash.get(ch)+1));
}
else
{
hash.put(ch, 1);
}
}
//Set set = hash.entrySet();
Entry<Character, Integer> maxEntry = null;
for(Entry<Character,Integer> entry : hash.entrySet())
{
if(maxEntry == null)
{
maxEntry = entry;
}
else if(maxEntry.getValue() < entry.getValue())
{
maxEntry = entry;
}
}
System.out.println(maxEntry.getKey());
}
public static void main(String[] args) {
Characterop op = new Characterop();
op.maxOccur("AABBBCCCCDDDDDDDDDD");
}
}
The Big O below solution is just o(n). Please share your opinion on it.
public class MaxOccuringCahrsInStr {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "This is Sarthak Gupta";
printMaxOccuringChars(str);
}
static void printMaxOccuringChars(String str) {
char[] arr = str.toCharArray();
/* Assuming all characters are ascii */
int[] arr1 = new int[256];
int maxoccuring = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] != ' ') { // ignoring space
int val = (int) arr[i];
arr1[val]++;
if (arr1[val] > maxoccuring) {
maxoccuring = arr1[val];
}
}
}
for (int k = 0; k < arr1.length; k++) {
if (maxoccuring == arr1[k]) {
char c = (char) k;
System.out.print(c + " ");
}
}
}
}
function countString(ss)
{
var maxChar='';
var maxCount=0;
for(var i=0;i<ss.length;i++)
{
var charCount=0;
var localChar=''
for(var j=i+1;j<ss.length;j++)
{
if(ss[i]!=' ' && ss[i] !=maxChar)
if(ss[i]==ss[j])
{
localChar=ss[i];
++charCount;
}
}
if(charCount>maxCount)
{
maxCount=charCount;
maxChar=localChar;
}
}
alert(maxCount+""+maxChar)
}
Another way to solve it. A simpler one.
public static void main(String[] args) {
String str= "aaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbcddddeeeeee";
String str1 = "dbc";
if(highestOccuredChar(str) != ' ')
System.out.println("Most Frequently occured Character ==> " +Character.toString(highestOccuredChar(str)));
else
System.out.println("The String doesn't have any character whose occurance is more than 1");
}
private static char highestOccuredChar(String str) {
int [] count = new int [256];
for ( int i=0 ;i<str.length() ; i++){
count[str.charAt(i)]++;
}
int max = -1 ;
char result = ' ' ;
for(int j =0 ;j<str.length() ; j++){
if(max < count[str.charAt(j)] && count[str.charAt(j)] > 1) {
max = count[str.charAt(j)];
result = str.charAt(j);
}
}
return result;
}
public void countOccurrence(String str){
int length = str.length();
char[] arr = str.toCharArray();
HashMap<Character, Integer> map = new HashMap<>();
int max = 0;
for (char ch : arr) {
if(ch == ' '){
continue;
}
if (map.containsKey(ch)) {
map.put(ch, map.get(ch) + 1);
} else {
map.put(ch, 1);
}
}
Set<Character> set = map.keySet();
for (char c : set) {
if (max == 0 || map.get(c) > max) {
max = map.get(c);
}
}
for (Character o : map.keySet()) {
if (map.get(o).equals(max)) {
System.out.println(o);
}
}
System.out.println("");
}
public static void main(String[] args) {
HighestOccurence ho = new HighestOccurence();
ho.countOccurrence("aabbbcde");
}
public void stringMostFrequentCharacter() {
String str = "My string lekdcd dljklskjffslk akdjfjdkjs skdjlaldkjfl;ak adkj;kfjflakj alkj;ljsfo^wiorufoi$*#&$ *******";
char[] chars = str.toCharArray(); //optionally - str.toLowerCase().toCharArray();
int unicodeMaxValue = 65535; // 4 bytes
int[] charCodes = new int[unicodeMaxValue];
for (char c: chars) {
charCodes[(int)c]++;
}
int maxValue = 0;
int maxIndex = 0;
for (int i = 0; i < unicodeMaxValue; i++) {
if (charCodes[i] > maxValue) {
maxValue = charCodes[i];
maxIndex = i;
}
}
char maxChar = (char)maxIndex;
System.out.println("The most frequent character is >" + maxChar + "< - # of times: " + maxValue);
}
For Simple String Manipulation, this program can be done as:
package abc;
import java.io.*;
public class highocc
{
public static void main(String args[])throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter any word : ");
String str=in.readLine();
str=str.toLowerCase();
int g=0,count,max=0;;
int ar[]=new int[26];
char ch[]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
for(int i=0;i<ch.length;i++)
{
count=0;
for(int j=0;j<str.length();j++)
{
char ch1=str.charAt(j);
if(ch[i]==ch1)
count++;
}
ar[i]=(int) count;
}
max=ar[0];
for(int j=1;j<26;j++)
{
if(max<ar[j])
{
max=ar[j];
g=j;
}
}
System.out.println("Maximum Occurence is "+max+" of character "+ch[g]);
}
}
Sample Input1: Pratik is a good Programmer
Sample Output1: Maximum Occurence is 3 of character a
Sample Input2: hello WORLD
Sample Output2: Maximum Occurence is 3 of character l
maxOccu m = new maxOccu();
String str = "moinnnnaaooooo";
char[] chars = str.toCharArray();
Arrays.sort(chars);
str = new String(chars);
System.out.println(str);
m.maxOccurence(str);
void maxOccurence(String str) {
char max_char = str.charAt(0),
cur_char,
prev = str.charAt(0);
int cur_count = 0,
max_count = 0,
n;
n = str.length();
for (int i = 0; i < n; i++) {
cur_char = str.charAt(i);
if (cur_char != prev) cur_count = 0;
if (str.charAt(i) == cur_char) {
cur_count++;
}
if (cur_count > max_count) {
max_count = cur_count;
max_char = cur_char;
}
prev = cur_char;
}
System.out.println(max_count + "" + max_char);
}
public class HigestOccurredCharTest {
public static void main(String[] args) {
System.out.println("Enter the char string to check higest occurrence");
Scanner scan = new Scanner(System.in);
String str = scan.next();
if(str != null && !str.isEmpty()){
Map<Character, Integer> map = countOccurrence(str);
getHigestOccurrenceChar(map);
}else{
System.out.println("enter valid string");
}
}
public static Map<Character, Integer> countOccurrence(String str){
char strArr[] = str.toCharArray();
Map<Character, Integer> map = new HashMap<Character , Integer>();
for (Character ch : strArr) {
if(map.containsKey(ch)){
map.put(ch, map.get(ch)+1);
}else{
map.put(ch, 1);
}
}
return map;
}
public static void getHigestOccurrenceChar(Map<Character, Integer> map){
Character ch = null;
Integer no = 0;
Set<Entry<Character, Integer>> entrySet = map.entrySet();
for (Entry<Character, Integer> entry : entrySet) {
if(no != 0 && ch != null){
if(entry.getValue() > no){
no = entry.getValue();
ch = entry.getKey();
}
}else{
no = entry.getValue();
ch = entry.getKey();
}
}
System.out.println(ch+ " Higest occurrence char is "+ no);
}
}
Try Like that:-
string inputString = "COMMECEMENT";
List<Tuple<char, int>> allCharListWithLength = new List<Tuple<char, int>>();
List<char> distinchtCharList = inputString.Select(r => r).Distinct().ToList();
for (int i = 0; i < distinchtCharList.Count; i++)
{
allCharListWithLength.Add(new Tuple<char, int>(distinchtCharList[i], inputString.Where(r => r ==
distinchtCharList[i]).Count()));
}
Tuple<char, int> charWithMaxLength = allCharListWithLength.Where(r => r.Item2 == allCharListWithLength.Max(x => x.Item2)).FirstOrDefault();
Question: Frequently occurring Character in a String
Method 1: Using HashMap
public class t1{
public static void main(String a[]){
Map<Character, Integer> map = new HashMap<>();
String a1 = "GiinnniiiiGiiinnnnnaaaProtijayi";
for(char ch : a1.toCharArray()) {map.put(ch, map.getOrDefault(ch,0)+1);}//for
System.out.println(map);
char maxchar = 0 ;
int maxvalue = Collections.max(map.values());
System.out.println("maxvalue => " + maxvalue);
for( Entry<Character,Integer> entry : map.entrySet()) {
if(entry.getValue() == maxvalue) {
System.out.println("most frequent Character => " + entry.getKey());
}
}//for
}
}
Method 2 : Using count of alphabets in Python
str = "GiinnniiiiGiiinnnnnaaaProtijayi";
count = [0]*256
maxcount= -1
longestcharacter =""
# Traversing through the string and maintaining the count of
# each character
for ch in str:count[ord(ch)] += 1;
for ch in str:
if( maxcount < count[ord(ch)] ):
maxcount = count[ord(ch)]
longestcharacter = ch
print(longestcharacter)
print(maxcount)
IN Java :
public class t1{
public static void main(String[] args) {
String a = "GiinnniiiiGiiinnnnnaaaProtijayi";
int[] count = new int[256];
for (int i = 0; i < a.length(); i++) {
char ch = a.charAt(i);
count[ch] +=1;
}//for
int maxcount = -1 ;
char longest = 0 ;
for( char ch : a.toCharArray()) {
if(count[ch] > maxcount) {
maxcount = count[ch];
longest = ch ;
}//if
}//for
System.out.println(longest);
System.out.println(maxcount);
}//main
}
Method 3: Using collections.Counter().most_common()
import collections
a = "GiinnniiiiGiiinnnnnaaaProtijayi";
fullDictionary = collections.Counter(a).most_common()
FirstElementWithCount = fullDictionary[0]
print(FirstElementWithCount)
FirstElementWithoutCount = FirstElementWithCount[0]
print(FirstElementWithoutCount)
Method 4: Using sorted and key = lambda ch : ch[1]
a = "GiinnniiiiGiiinnnnnaaaProtijayi";
d = {}
for ch in a: d[ch] = d.get(ch, 0) + 1
fullDictionary = sorted(d.items(), key=lambda ch :ch[1], reverse=True)
print(fullDictionary)
FirstElement = fullDictionary[0][0]
print(FirstElement)
package com.practice.ArunS;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
public class HighestFrequencyElement {
/*
* CONTENTSERV=N(2),T(2),E(2) SearchSort=S(2),r(2)
* HighestFrequencyElement=E(5)
*/
public static void main(String[] args) {
String str = "CONTENTSERV";
findHighestFrequencyElement(str);
}
private static void findHighestFrequencyElement(String str) {
System.out.println("Original String:" + str);
Map<String, Integer> myMap = new TreeMap<String, Integer>();
char[] ch = str.toCharArray();
for (int i = 0; i < str.length(); i++) {
if (myMap.containsKey(Character.toString(ch[i]))) {
Integer value = myMap.get(Character.toString(ch[i]));
myMap.replace(Character.toString(ch[i]), ++value);
} else {
myMap.put(Character.toString(ch[i]), 1);
}
} // end of foor loop
Comparator<Entry<String, Integer>> valueComparator = new Comparator<Entry<String, Integer>>() {
#Override
public int compare(Entry<String, Integer> e1, Entry<String, Integer> e2) {
Integer v1 = e1.getValue();
Integer v2 = e2.getValue();
return v2-v1;
}
};
// Sort method needs a List, so let's first convert Set to List in Java
List<Entry<String, Integer>> listOfEntries = new ArrayList<Entry<String, Integer>>(myMap.entrySet());
// sorting HashMap by values using comparator
Collections.sort(listOfEntries, valueComparator);
for(int i=0;i<listOfEntries.size();i++){
if(listOfEntries.get(0).getValue()==listOfEntries.get(i).getValue()){
System.out.println(listOfEntries.get(i));
}
}
}//end of method
}
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class Answers {
public static void main(String[] args) {
String input1 = "Hello! Are you all fine? What are u doing today? Hey Guyz,Listen! I have a plan for today.";
String[] arin = input1.split("");
Predicate<String> checkIfValidChar = str -> ((str.charAt(0) >= '0' && str.charAt(0) <= '9')
|| (str.charAt(0) >= 'a' && str.charAt(0) <= 'z')
|| (str.charAt(0) >= 'A' && str.charAt(0) <= 'Z'));
String maxChar = Arrays.stream(arin).max(Comparator.comparing(i -> Arrays.stream(arin).filter(j -> {
return i.equalsIgnoreCase(j) && checkIfValidChar.test(j);
}).count())).get();
int count = Collections.frequency(Arrays.asList(arin), maxChar);
System.out.println(Arrays.stream(arin).filter(i -> {
return Collections.frequency(Arrays.asList(arin), i) == count && checkIfValidChar.test(i);
}).collect(Collectors.toSet()));
}
}
I see many answers that are unnecessarily convoluted, import tons of stuff or use a cannon to shoot a mosquito ( the accepted answer uses an HashTable ).
Here a simple solution:
public List<Character> mostFrequentLetter(String message) {
var m = message
.replaceAll("[^a-z]", "")
.toLowerCase();
int[] count = new int[26];
for(var c : m.toCharArray()){
int i = ((int)c)-97;
count[i]++;
}
var max_i = 0; // index of the most frequent letter
var max_c = count[max_i]; // count of the most frequent letter
var max = new ArrayList<Character>(3); // list containing letters with the same frequency
for(int i = 1; i < 26; ++i){
if (count[i] >= max_c){
max_i = i;
char c = (char)(max_i + 97);
if(count[i]!=max_c){
max.clear();
max_c = count[i];
}
max.add(c);
}
}
return max;
}
Here str will be the given string. This is Javascript code
function maxCharacter(str){
let str1 = str; let reptCharsCount=0; let ele='';let maxCount=0;
let charArr = str1.split('');
for(let i=0; i< str1.length; i++){
reptCharsCount=0;
for(let j=0; j< str1.length; j++){
if(str1[i] === str1[j]) {
reptCharsCount++;
}
}
if(reptCharsCount > maxCount) {
ele = str1[i];
maxCount = reptCharsCount;
}
}
return ele;
}
Although all the answers are correct posting my way of doing it
/Question: For the given string such as "aabbbbbcc" print the longest occurring character,
index and number of times it occurs.
Ex:
"longest occurring character is b and length is 5 at index 2"./
class Codechef {
public static void main (String[] args) {
String problem = "aabbbbbcc";
Map<Character,Temp> map = new HashMap<>();
for(int i = 0; i < problem.length(); i++){
if (map.containsKey(problem.charAt(i))) {
map.get(problem.charAt(i)).incrementCount();
} else {
map.put(problem.charAt(i), new Temp(i, 1, problem.charAt(i)));
}
}
List<Map.Entry<Character, Temp>> listOfValue = new LinkedList<Map.Entry<Character, Temp>>(map.entrySet());
Comparator<Map.Entry<Character, Temp>> comp = (val1, val2) -> (val1.getValue().getCount() < val2.getValue().getCount() ? 1: -1);
Collections.sort(listOfValue, comp);
Temp tmp = listOfValue.get(0).getValue();
System.out.println("longest occurring character is "+ tmp.getStr()+ " and length is " + tmp.getCount()+ " at index "+ tmp.getIndex());
}}
And then created one Model class to keep these values
class Temp {
Integer index;
Integer count;
Character str;
public Temp(Integer index, Integer count, Character str ){
this.index = index;
this.count = count;
this.str = str;
}
public void incrementCount(){
this.count++;
}
public Integer getCount(){
return count;
}
public Character getStr(){
return str;
}
public Integer getIndex(){
return index;
}}
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
public class Maxchar {
public static void main(String[] args) {
String str = "vaquar khan.";
// System.out.println();
System.out.println(maxChar(str));
String testcase1 = "Hello! Are you all fine? What are u doing today? Hey Guyz,Listen! I have a plan for today.";
System.out.println(maxChar(testcase1));
}
private static char maxChar(String str) {
if (null == str)
return ' ';
char[] charArray = str.replaceAll("\s+", "").toCharArray();
//
Map<Character, Integer> maxcharmap = new HashMap<Character, Integer>();
//
for (char c : charArray) {
if (maxcharmap.containsKey(c)) {
maxcharmap.put(c, maxcharmap.get(c) + 1);
} else {
maxcharmap.put(c, 1);
}
// Inside map we have word count
// System.out.println(maxcharmap.toString());
}
//
//
Set<Entry<Character, Integer>> entrySet = maxcharmap.entrySet();
int count = 0;
char maxChar = 0;
//
for (Entry<Character, Integer> entry : entrySet) {
if (entry.getValue() > count) {
count = entry.getValue();
maxChar = entry.getKey();
}
}
System.out.println("Maximum Occurring char and its count :");
System.out.println(maxChar + " : " + count);
return maxChar;
}
}
If you're open to 3rd party libraries you could use the Bag type from Eclipse Collections and select the top occurrences.
public char[] maxOccurringChar(String s) {
MutableCharBag bag = CharBags.mutable.of(s.toCharArray());
MutableList<CharIntPair> maxOccurringCharsWithCounts = bag.topOccurrences(1);
MutableCharList maxOccurringChars = maxOccurringCharsWithCounts.collectChar(CharIntPair::getOne);
return maxOccurringChars.toArray();
}
Note in this example we used the primitive collections to avoid boxing of the char and int types.
import java.util.*;
import java.util.stream.*;
class MaxOccur{
public static void main(String[] args){
String str = "sfowfjalkfaeffawkefjweajjwjegjoweeowe";
maxOcc(str);
}
public static void maxOcc(String s){
ArrayList<Character> arr = (ArrayList<Character>) s.chars().mapToObj(e ->(char)e).collect(Collectors.toList());
HashSet<Character> hs = new HashSet<>(arr);
int max = 0;
int f = 0;
String answer = "";
for(Character ch : hs){
f = Collections.frequency(arr,ch);
if(f>max){
max = f;
answer = ch;
}
System.out.println(ch + " occurs " + max + " times, the maximum");
}
}
In above, I'm using streams. Following are the steps:
Converting string's characters to arraylist using streams.
Making a hashset (discards all duplicate occurences of characters) using the arrayList created in step 1.
Use Collections.frequency to count occurence of each character in arrayList.
It's not the easiest solution, neither is it really adorable! But, it makes use of streams, something which i recently started learning and wanted to apply. I'm no adept in using streams, but they are beautiful. I've learnt most of them here on stackoverflow, and i'm so grateful. :)
Map the chars to their occurrence then query entries for the max value and get its key, note this will return the first char that has the highest occurrence
"abc".chars().mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(Function.identity(),Collectors.counting()))
.entrySet()
.stream()
.max(Comparator.comparingLong(Map.Entry::getValue))
.get()
.getKey();
Here I am posting the answer by using HashMap
public class maximumOccurrence {
public static Map<Character,Integer> maximumOccurence(String s) {
char maxchar='';
int maxint=0;
Map<Character,Integer> map = new HashMap<Character, Integer>();
char strAtt[]= s.toCharArray();
for(Character ch : strAtt) {
if(map.containsKey(ch)) {
map.put(ch, map.get(ch)+1);
}else {
map.put(ch,1);
}
}
for(Map.Entry<Character,Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + "/" + entry.getValue());
if(maxint<entry.getValue()) {
maxint=entry.getValue();
maxchar=entry.getKey();
}
}
System.out.println("Character repeated ="+maxchar+" it's value is:"+maxint);
return map;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String s= "uuuiiiiiiiiiiioooooopp";
System.out.println(maximumOccurence(s));
}
}

How to return longest sequence of chars in a string in java?

Following is what I end up doing but i did not find right answer.
Example - If I have the sequence "hellloo" the output will be "lll". Please tell me what is wrong?
public class LongestSequenceOfChar {
static String testcase1="hellloo";
public static void main(String[] args) {
LongestSequenceOfChar test = new LongestSequenceOfChar();
String result = test.longestSequenceOfChar(testcase1);
System.out.println(result);
}
public String longestSequenceOfChar(String str){
String result="";
for(int i=0;i<str.length();i++){
char ch=str.charAt(i);
for(int j=i+1;j<str.length();j++){
char ch1=str.charAt(j);
if(ch!=ch1){
continue;
}
result+=ch;
}
}
return result;
}
}
You should have a counter that counts the number of the longest sequence for now. When you find a longer sequence, you should reset result and update the counter accordingly.
However, you can have better solutions:
Have an array of size 26 (the size of the English alphabet). Now you iterate on the String and for each char in it you add 1 in the corresponding cell in the helper array.
Use a HashMap that has the char as a key and the number it appears as the value. If it's a new char you simply put it with 0 value, if it exists, you increment the existing value.
Tip: Use a debugger, it can save your life.
1. Create a HashMap<Character,Integer>.. Integer-->count
2. Start from the beginning of your String.. For each character, check if it is already present in the hashmap
a. If Yes, just increment the count
b. if No, then add the character as key to the Map and set its count value to 1.
If there are three 'l' you only add two and in the next step are two 'l' and you add one of them. Then the same with the two 'o' where you are adding one. You only have to clear the result string when you step to the next letter and before save the result in another variable, but only if its is longer!
public String longestSequenceOfChar(String str){
String interimresult="";
String result=""; //final result
for(int i=0;i<str.length();i++){
char ch=str.charAt(i);
interimresult += ch; //add the letter once
for(int j=i+1;j<str.length();j++){
char ch1=str.charAt(j);
if(ch!=ch1){
break;
}
interimresult +=ch;
}
if(interimresult.length()>result.length())//store the result if it is longer
result = interimresult;
interimresult = ""; //clear to continue with the next letter
}
return result;
}
Here is a solution:
public String longestSequenceOfChar(String str) {
String result = "";
for (int i = 0; i < str.length(); i++) {
int j = i;
while(j < str.length() && str.charAt(j) == str.charAt(i)) {
j++;
}
// If this one is longer than previous, then asign it to result.
if(j - i > result.length()) {
result = str.substring(i, j);
}
}
return result;
}
This can be solved easily using HashMap. Checkout this sample code:
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class MaximumOccuringCharUsingHashMap {
public static void main(String[] args) {
String test = "test samples";
MaximumOccuringCharUsingHashMap mc =
new MaximumOccuringCharUsingHashMap();
System.out.println( mc.findMaximunOccurenceCharacter(test));
}
char findMaximunOccurenceCharacter(String input){
Map<Character, Integer> countHash =
new HashMap<Character, Integer>();
for(int i=0; i<input.length() ;i++ ){
char currentChar = input.charAt(i);
if(countHash.get(currentChar)==null){
countHash.put(currentChar, 1);
}else{
countHash.
put(currentChar, countHash.get(currentChar)+1);
}
}
int max = Collections.max(countHash.values());
char maxCharacter =0;
for(Entry<Character, Integer> entry :countHash.entrySet()){
if(entry.getValue() == max){
maxCharacter = entry.getKey();
}
}
return maxCharacter;
}
}
Above code will print s as output, which is occurring maximum number of times in the given String.
Try This...
public class HelloWorld {
public static void main(String[] args) {
System.out.println(maxLen(null));
System.out.println(maxLen(""));
System.out.println(maxLen("a"));
System.out.println(maxLen("aa"));
System.out.println(maxLen("abcddd"));
System.out.println(maxLen("abcd"));
System.out.println(maxLen("aabbba"));
}
public static String maxLen(String input) {
// Avoid NPEs
if (input == null) {
return null;
}
int maxLen = 0;
int tempLen = 0;
char prevChar = 0;
char c = 0;
char repeatChar = 0;
for (int i = 0; i < input.length(); i++) {
c = input.charAt(i);
if (c == prevChar) {
tempLen++;
if (tempLen > maxLen)
repeatChar = c;
} else {
maxLen = (tempLen > maxLen) ? tempLen : maxLen;
prevChar = c;
tempLen = 1;
}
}
maxLen = (tempLen > maxLen) ? tempLen : maxLen;
if (maxLen == 0 || maxLen == 1)
return "no sequence found";
else {
String str = "";
for (int i = 1; i <= maxLen; i++)
str += String.valueOf(repeatChar);
return str;
}
}
}
This will pass all test cases.

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