I'm trying to search of multiple words given from a user ( i used array to store them in ) from one txt file , and then if that word presented once in the file it will be displayed and if it's not it won't.
also for the words itself , if it's duplicated it will search it once.
the problem now when i search for only one it worked , but with multiple words it keeps repeated that the word isn't present even if it's there.
i would like to know where should i put the for loop and what's the possible changes.
package search;
import java.io.*;
import java.util.Scanner;
public class Read {
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner(System.in);
String[] words=null;
FileReader fr = new FileReader("java.txt");
BufferedReader br = new BufferedReader(fr);
String s;
System.out.println("Enter the number of words:");
Integer n = sc.nextInt();
String wordsArray[] = new String[n];
System.out.println("Enter words:");
for(int i=0; i<n; i++)
{
wordsArray[i]=sc.next();
}
for (int i = 0; i <n; i++) {
int count=0; //Intialize the word to zero
while((s=br.readLine())!=null) //Reading Content from the file
{
{
words=s.split(" "); //Split the word using space
for (String word : words)
{
if (word.equals(wordsArray[i])) //Search for the given word
{
count++; //If Present increase the count by one
}
}
if(count == 1)
{
System.out.println(wordsArray[i] + " is unique in file ");
}
else if (count == 0)
{
System.out.println("The given word is not present in the file");
}
else
{
System.out.println("The given word is present in the file more than 1 time");
}
}
}
}
fr.close();
}
}
The code which you wrote is error prone and remember always there should be proper break condition when you use while loop.
Try the following code:
public class Read {
public static void main(String[] args)
{
// Declaring the String
String paragraph = "These words can be searched";
// Declaring a HashMap of <String, Integer>
Map<String, Integer> hashMap = new HashMap<>();
// Splitting the words of string
// and storing them in the array.
String[] words = new String[]{"These", "can", "searched"};
for (String word : words) {
// Asking whether the HashMap contains the
// key or not. Will return null if not.
Integer integer = hashMap.get(word);
if (integer == null)
// Storing the word as key and its
// occurrence as value in the HashMap.
hashMap.put(word, 1);
else {
// Incrementing the value if the word
// is already present in the HashMap.
hashMap.put(word, integer + 1);
}
}
System.out.println(hashMap);
}
}
I've tried by hard coding the values, you can take words and paragraph from the file and console.
The 'proper' class to use for extracting words from text is java.text.BreakIterator
You can try the following (reading line-wise in case of large files)
import java.text.BreakIterator;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import java.nio.file.Files;
import java.nio.file.Paths;
public class WordFinder {
public static void main(String[] args) {
try {
if (args.length < 2) {
WordFinder.usage();
System.exit(1);
}
ArrayList<String> argv = new ArrayList<>(Arrays.asList(args));
String path = argv.remove(0);
List<String> found = WordFinder.findWords(Files.lines(Paths.get(path)), argv);
System.out.printf("Found the following word(s) in file at %s%n", path);
System.out.println(found);
} catch (Throwable t) {
t.printStackTrace();
}
}
public static List<String> findWords(Stream<String> lines, ArrayList<String> searchWords) {
List<String> result = new ArrayList<>();
BreakIterator boundary = BreakIterator.getWordInstance();
lines.forEach(line -> {
boundary.setText(line);
int start = boundary.first();
for (int end = boundary.next(); end != BreakIterator.DONE; start = end, end = boundary.next()) {
String candidate = line.substring(start, end);
if (searchWords.contains(candidate)) {
result.add(candidate);
searchWords.remove(candidate);
}
}
});
return result;
}
private static void usage() {
System.err.println("Usage: java WordFinder <Path to input file> <Word 1> [<Word 2> <Word 3>...]");
}
}
Sample run:
goose#t410:/tmp$ echo 'the quick brown fox jumps over the lazy dog' >quick.txt
goose#t410:/tmp$ java WordFinder quick.txt dog goose the did quick over
Found the following word(s) in file at quick.txt
[the, quick, over, dog]
goose#t410:/tmp$
I am trying to write a program that has the method public static void method(List<String> words) where the parameter words is a list of words from the text file words.txt that are sorted and contain only the words where each letter occurs only once. For example, the word "feel" would not be included in this list since "e" occurs more than once. The word list is not to be used as an argument in the rest of the program, so the method method is only to be used to store and remember the wordlist for later use. This function can also perform any of the sorting methods.
My thought process was to create a method that would read the text file, and use that text file as the argument in method. method would then filter out all words with letters that appear more than once, and also sort the new list.
When running the program, I'm getting an error "java.util.ConcurrentModificationException: null (in java.util.LinkedList$Listltr)" on the line for (String word : words). Also does the line public static List list; properly save and store the list for later use?
import java.util.*;
import java.io.*;
class ABC
{
public static List<String> list = new LinkedList<String>()
public static List readFile()
{
String content = new String();
File file = new File("words.txt");
LinkedList<String> words = new LinkedList<String>();
try
{
Scanner sc = new Scanner(new FileInputStream(file));
while (sc.hasNextLine())
{
content = sc.nextLine();
words.add(content);
}
}
catch (FileNotFoundException fnf)
{
fnf.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("\nProgram terminated safely");
}
for (String word : words)
{
if (letters(word) == false)
{
list.add(word);
}
}
Collections.sort(list);
return list;
}
public static boolean letters(String word)
{
for (int i = 0; i < word.length() - 1; i++)
{
if (word.contains(String.valueOf(word.charAt(i))) == true)
{
return true;
}
}
return false;
}
public static void main(String args[])
{
System.out.println(readFile());
}
}
The source of the error is that you are changing a list that you are iterating on. This is generally not a good idea.
Since you are building a new list, you don't actually need to change the one you are iterating on. I would recommend changing your code so that the logic for deciding if a letter appears more than once goes in a separate method. This way the complexity of any given method is manageable, and you can test them separately.
So create a new method that tests if any letter appears more than once:
static boolean doesAnyLetterAppearMoreThanOnce(String word) {
...
}
Then you can use it in your existing method:
for (String word : words) {
if (!doesAnyLetterAppearMoreThanOnce(word)) {
list.add(word);
}
}
Collections.sort(list);
Use an iterator. Try it like this.
Iterator<String> it = words.iterator();
while(it.hasNext()) {
CharSequence ch = it.next();
for (int j = 0; j < ch.length(); j++)
{
for (int k = j + 1; k < ch.length(); k++)
{
if (ch.charAt(j) == ch.charAt(k))
{
it.remove(word);
}
}
}
list.add(word);
}
However, I would approach it differently.
String[] data =
{ "hello", "bad", "bye", "computer", "feel", "glee" };
outer: for (String word : data) {
for (int i = 0; i < word.length() - 1; i++) {
if (word.charAt(i) == word.charAt(i + 1)) {
System.out.println("dropping '" + word + "'");
continue outer;
}
}
System.out.println("Keeping '" + word + "'");
List.add(word);
}
Note: You used feel as an example so it wasn't clear if you wanted to check for the same letter anywhere in the word or only adjacent letters that are the same.
There are several problems with you program:
public static List list;
Whenever you see a collection (like List) without a generics - it's a bad smell. Should be public static List<String> list;
Also consider changing public to private.
In readFile() method you mask the class variable 'list' with a local variable 'list'. So your class variable remains uninitialized:
list = new LinkedList<String>();
Better use try-with-resources for scanner:
try(Scanner sc = new Scanner(new FileInputStream(file))) {
You don't need to close it afterwards manually.
You cannot modify the list through which you are iterating. You should either use an iterator and its remove method, or create a new list and append good words to it, instead of removing bad words from the original list.
public static List<String> readFile() {
File file = new File("words.txt");
List<String> list = new ArrayList<>();
try (Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine()) {
String word = scanner.nextLine();
if (noDuplicates(word)) {
list.add(word);
}
}
Collections.sort(list);
} catch (FileNotFoundException e) {
System.out.println("File not found");
}
return list;
}
private static boolean noDuplicates(String word) {
Set<Character> distinctChars = new HashSet<>();
for (char c : word.toCharArray()) {
if (!distinctChars.add(c)) {
return false;
}
}
return true;
}
I suggest this shorter approach:
public static void method(List<String> words) {
words.removeIf(word -> {
Set<Integer> hs = new HashSet<>();
return word.chars().anyMatch(c -> {
if (hs.contains(c)) return true;
else hs.add(c);
return false;
});
});
System.out.println(words);}
words List now contain only the words where each letter occurs only once.
Hey i am beginner in java programming and i have written a program to count the number of occurrence in string and i want to improve this code.
import java.io.*;
public class Letters
{
public static void main(String let[]) throws IOException
{
InputStreamReader r = new InputStreamReader(System.in);
BufferedReader b = new BufferedReader(r);
System.out.println("Enter The Sentense");
String s = b.readLine();
String store="";
String store1="";
for(int i=0;i<=s.length()-1;i++)
{
int count =0;
store=s.charAt(i)+"";
for(int j=0;j<=s.length()-1;j++)
{
store1=s.charAt(j)+"";
if(store.equals(store1))
{
++count;
}
}
System.out.println(store+" : "+count);
}
}
}
And output i am getting for this is
Enter The Sentense
ddooooonnneeeeee
d : 2
d : 2
o : 5
o : 5
o : 5
o : 5
o : 5
n : 3
n : 3
n : 3
e : 6
e : 6
e : 6
e : 6
e : 6
e : 6
But i want to get my output like this
Enter The Sentense
ddooooonnneeeeee
d:2
o:5
n:3
e:6
Any suggestion how can i do it.
The following code will help you in achieving this using HashMap Collection which will not allow duplicate keys.
import java.util.HashMap;
import java.util.Scanner;
public class Letters {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter The Sentense");
String s = in.nextLine();
HashMap<Character,Integer> w = new HashMap<Character,Integer>();
for(int i=0; i < s.length(); i++){
w.put(s.charAt(i), w.get(s.charAt(i))==null?1:(w.get(s.charAt(i))+1));
}
for(char i:w.keySet()){
System.out.println(i+":"+w.get(i));
}
}
}
Take a character array instead which keeps a track of each alphabet.
Something like
int countLetter[] = new int[26];
then
for(int i=0;i<=s.length()-1;i++)
{
countLetter[s.charAt(i) - 97] ++;
}
Then print the contents
You could have a HashMap whose key is the character you want to count and each time you encounter that character you simply update (+1) the value of the HashMap with the count/occurrences.
Here is an example:
//the frequency hashMap
HashMap<String, Integer> characterFrequencyMap = new HashMap<String, Integer>();
//here you reach characters of your string
for(int x=0; x< s.length; x++){
if(!s[x].equalsIgnoreCase(" ") )
updateFrequencies(s[x].toLowerCase());
}
Finally, this is the function that updates the character frequency
private void updateFrequencies(String keyCharacter){
if(characterFrequencyMap.containsKey(keyCharacter)){
int currentFrequency = characterFrequencyMap.get(keyCharacter);
characterFrequencyMap.replace(keyCharacter, currentFrequency+1);
}
else{
characterFrequencyMap.put(keyCharacter, 1);
}
}
I hope this helps. Please give it a try and let me know.
import java.io.*;
import java.util.TreeSet;
public class Letters
{
public static void main(String let[]) throws IOException
{
InputStreamReader r = new InputStreamReader(System.in);
BufferedReader b = new BufferedReader(r);
System.out.println("Enter The Sentense");
String s = b.readLine();
String store="";
String store1="";
TreeSet<String> ts = new TreeSet<String>();
for(int i=0;i<=s.length()-1;i++)
{
int count =0;
store=s.charAt(i)+"";
if(ts.contains(store) == false)
{
for(int j=0;j<=s.length()-1;j++)
{
store1=s.charAt(j)+"";
if(store.equals(store1))
{
++count;
}
}
System.out.println(store+" : "+count);
ts.add(store);
}
}
}
}
I have a HashMap
HashMap<String, LinkedList<Integer>> indexMap;
which is storing all words in a file and their corresponding line numbers where they appear.
Example -
This is just an example
to demonstrate what I am saying an is
Would display
This [1]
demonstrate [2]
an [1 2]
is [1 2]
...
....
And so on. I want to reverse this HashMap so that it displays the words stored at each line number.
For the particular example above, it should display
1 [This, an, just, example, is]
2 [demonstrate, what, to, I, am, saying, is, an]
For this particular task, this is what I have done -
import java.io.FileReader;
import java.io.LineNumberReader;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
public class ReverseIndex {
private static Map<String, LinkedList<Integer>> indexMap = new HashMap<String, LinkedList<Integer>>();
public static LinkedList<Integer> getIndex(String word) {
return indexMap.get(word);
}
public static void main(String[] args) {
try {
LineNumberReader rdr = new LineNumberReader(
new FileReader(
args[0]));
String line = "";
int lineNumber = 0;
//CREATING THE INITIAL HASHMAP WHICH WE WANT TO REVERSE
while ((line = rdr.readLine()) != null) {
lineNumber++;
String[] words = line.split("\\s+");
for (int i = 0; i < words.length; i++) {
LinkedList<Integer> temp = new LinkedList<Integer>();
if (getIndex(words[i]) != null)
temp = getIndex(words[i]);
temp.add(lineNumber);
indexMap.put(words[i], temp);
}
}
//FINISHED CREATION
Map<Integer, LinkedList<String>> myNewHashMap = new HashMap<Integer, LinkedList<String>>();
for(Map.Entry<String, LinkedList<Integer>> entry : indexMap.entrySet()){
LinkedList<Integer> values = entry.getValue();
String key = entry.getKey();
LinkedList<String> temp = new LinkedList<String>();
for(int i = 0; i <= lineNumber; i++) {
if(values.contains(i)) {
if(!temp.contains(key))
temp.add(key);
myNewHashMap.put(i, temp);
}
}
}
for(Map.Entry<Integer, LinkedList<String>> entry : myNewHashMap.entrySet()){
Integer tester = entry.getKey();
LinkedList<String> temp2 = new LinkedList<String>();
temp2 = entry.getValue();
System.out.print(tester + " ");
for(int i = 0; i < temp2.size(); i++) {
System.out.print(temp2.get(i) + " ");
}
System.out.println();
}
rdr.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
However the problem with this is, for the example that we had above, it would print -
1 example
2 an
How could I reverse it so that it works perfectly with the expected output?
Just replace the first for loop in your main with the below code. I have made some changes to you original code as per convention like moved variable declaration out of loop and changed the logic in a way it checks if the LinkedList<'String'> already exists for the line number if so add it to the list or else create a new LinkedList<'String'> and then add word.
LinkedList<Integer> values = null;
String key = null;
LinkedList<String> temp = null;
for(Map.Entry<String, LinkedList<Integer>> entry : indexMap.entrySet())
{
values = entry.getValue();
key = entry.getKey();
temp = new LinkedList<String>();
for(int value : values)
{
temp = myNewHashMap.get(value);
if(temp == null )
{
temp = new LinkedList<String>();
myNewHashMap.put(value,temp);
}
temp.add(key);
}
}
I need to write some kind of loop that can count the frequency of each letter in a string.
For example: "aasjjikkk" would count 2 'a', 1 's', 2 'j', 1 'i', 3 'k'. Ultimately id like these to end up in a map with the character as the key and the count as the value. Any good idea how to do this?
You can use a java Map and map a char to an int. You can then iterate over the characters in the string and check if they have been added to the map, if they have, you can then increment its value.
For example:
Map<Character, Integer> map = new HashMap<Character, Integer>();
String s = "aasjjikkk";
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
Integer val = map.get(c);
if (val != null) {
map.put(c, val + 1);
}
else {
map.put(c, 1);
}
}
At the end you will have a count of all the characters you encountered and you can extract their frequencies from that.
Alternatively, you can use Bozho's solution of using a Multiset and counting the total occurences.
Using the stream API as of JDK-8:
Map<Character, Long> frequency =
str.chars()
.mapToObj(c -> (char)c)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
or if you want the keys as Integers:
Map<Character, Integer> frequency =
str.chars()
.mapToObj(c -> (char)c)
.collect(Collectors.groupingBy(Function.identity(), Collectors.summingInt(c -> 1)));
Another variant:
Map<Character, Integer> frequency =
str.chars()
.mapToObj(c -> (char)c)
.collect(Collectors.toMap(Function.identity(), c -> 1, Math::addExact));
A concise way to do this is:
Map<Character,Integer> frequencies = new HashMap<>();
for (char ch : input.toCharArray())
frequencies.put(ch, frequencies.getOrDefault(ch, 0) + 1);
We use a for-each to loop through every character. The frequencies.getOrDefault() gets value if key is present or returns(as default) its second argument.
You can use a Multiset (from guava). It will give you the count for each object. For example:
Multiset<Character> chars = HashMultiset.create();
for (int i = 0; i < string.length(); i++) {
chars.add(string.charAt(i));
}
Then for each character you can call chars.count('a') and it returns the number of occurrences
Here is another solution, dodgy as it may be.
public char getNumChar(String s) {
char[] c = s.toCharArray();
String alphabet = "abcdefghijklmnopqrstuvwxyz";
int[] countArray = new int[26];
for (char x : c) {
for (int i = 0; i < alphabet.length(); i++) {
if (alphabet.charAt(i) == x) {
countArray[i]++;
}
}
}
java.util.HashMap<Integer, Character> countList = new java.util.HashMap<Integer, Character>();
for (int i = 0; i < 26; i++) {
countList.put(countArray[i], alphabet.charAt(i));
}
java.util.Arrays.sort(countArray);
int max = countArray[25];
return countList.get(max);
}
Since there was no Java 8 solution, thought of posting one. Also, this solution is much neater, readable and concise than some of the other solutions mentioned here.
String string = "aasjjikkk";
Map<Character, Long> characterFrequency = string.chars() // creates an IntStream
.mapToObj(c -> (char) c) // converts the IntStream to Stream<Character>
.collect(Collectors.groupingBy(c -> c, Collectors.counting())); // creates a
// Map<Character, Long>
// where the Long is
// the frequency
Well, two ways come to mind and it depends on your preference:
Sort the array by characters. Then, counting each character becomes trivial. But you will have to make a copy of the array first.
Create another integer array of size 26 (say freq) and str is the array of characters.
for(int i = 0; i < str.length; i ++)
freq[str[i] - 'a'] ++; //Assuming all characters are in lower case
So the number of 'a' 's will be stored at freq[0] and the number of 'z' 's will be at freq[25]
Here is a solution:
Define your own Pair:
public class Pair
{
private char letter;
private int count;
public Pair(char letter, int count)
{
this.letter = letter;
this.count= count;
}
public char getLetter(){return key;}
public int getCount(){return count;}
}
Then you could do:
public static Pair countCharFreq(String s)
{
String temp = s;
java.util.List<Pair> list = new java.util.ArrayList<Pair>();
while(temp.length() != 0)
{
list.add(new Pair(temp.charAt(0), countOccurrences(temp, temp.charAt(0))));
temp.replaceAll("[" + temp.charAt(0) +"]","");
}
}
public static int countOccurrences(String s, char c)
{
int count = 0;
for(int i = 0; i < s.length(); i++)
{
if(s.charAt(i) == c) count++;
}
return count;
}
String s = "aaaabbbbcccddddd";
Map<Character, Integer> map = new HashMap<>();
Using one line in Java8
s.chars().forEach(e->map.put((char)e, map.getOrDefault((char)e, 0) + 1));
You can use a CharAdapter and a CharBag from Eclipse Collections and avoid boxing to Character and Integer.
CharBag bag = Strings.asChars("aasjjikkk").toBag();
Assert.assertEquals(2, bag.occurrencesOf('a'));
Assert.assertEquals(1, bag.occurrencesOf('s'));
Assert.assertEquals(2, bag.occurrencesOf('j'));
Assert.assertEquals(1, bag.occurrencesOf('i'));
Assert.assertEquals(3, bag.occurrencesOf('k'));
Note: I am a committer for Eclipse Collections.
There is one more option and it looks quite nice.
Since java 8 there is new method merge java doc
public static void main(String[] args) {
String s = "aaabbbcca";
Map<Character, Integer> freqMap = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
Character c = s.charAt(i);
freqMap.merge(c, 1, (a, b) -> a + b);
}
freqMap.forEach((k, v) -> System.out.println(k + " and " + v));
}
Or even cleaner with ForEach
for (Character c : s.toCharArray()) {
freqMapSecond.merge(c, 1, Integer::sum);
}
package com.rishi.zava;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class ZipString {
public static void main(String arg[]) {
String input = "aaaajjjgggtttssvvkkllaaiiikk";
int len = input.length();
Map<Character, Integer> zip = new HashMap<Character, Integer>();
for (int j = 0; len > j; j++) {
int count = 0;
for (int i = 0; len > i; i++) {
if (input.charAt(j) == input.charAt(i)) {
count++;
}
}
zip.put(input.charAt(j), count);
}
StringBuffer myValue = new StringBuffer();
String myMapKeyValue = "";
for (Entry<Character, Integer> entry : zip.entrySet()) {
myMapKeyValue = Character.toString(entry.getKey()).concat(
Integer.toString(entry.getValue()));
myValue.append(myMapKeyValue);
}
System.out.println(myValue);
}
}
Input = aaaajjjgggtttssvvkkllaaiiikk
Output = a6s2t3v2g3i3j3k4l2
If this does not need to be super-fast just create an array of integers, one integer for each letter (only alphabetic so 2*26 integers? or any binary data possible?). go through the string one char at a time, get the index of the responsible integer (e.g. if you only have alphabetic chars you can have 'A' be at index 0 and get that index by subtracting any 'A' to 'Z' by 'A' just as an example of how you can get reasonably fast indices) and increment the value in that index.
There are various micro-optimizations to make this faster (if necessary).
You can use a Hashtable with each character as the key and the total count becomes the value.
Hashtable<Character,Integer> table = new Hashtable<Character,Integer>();
String str = "aasjjikkk";
for( c in str ) {
if( table.get(c) == null )
table.put(c,1);
else
table.put(c,table.get(c) + 1);
}
for( elem in table ) {
println "elem:" + elem;
}
This is similar to xunil154's answer, except that a string is made a char array and a linked hashmap is used to maintain the insertion order of the characters.
String text = "aasjjikkk";
char[] charArray = text.toCharArray();
Map<Character, Integer> freqList = new LinkedHashMap<Character, Integer>();
for(char key : charArray) {
if(freqList.containsKey(key)) {
freqList.put(key, freqList.get(key) + 1);
} else
freqList.put(key, 1);
}
import java.util.*;
class Charfrequency
{
public static void main(String a[]){
Scanner sc=new Scanner(System.in);
System.out.println("Enter Your String :");
String s1=sc.nextLine();
int count,j=1;
char var='a';
char ch[]=s1.toCharArray();
while(j<=26)
{
count=0;
for(int i=0; i<s1.length(); i++)
{
if(ch[i]==var || ch[i]==var-32)
{
count++;
}
}
if(count>0){
System.out.println("Frequency of "+var+" is "+count);
}
var++;
j++;
}
}
}
The shorted possible code using a HashMap. (With no forceful line saves)
private static Map<Character, Integer> findCharacterFrequency(String str) {
Map<Character, Integer> map = new HashMap<>();
for (char ch : str.toCharArray()) {
/* Using getOrDefault(), since Java1.8 */
map.put(ch, map.getOrDefault(ch, 0) + 1);
}
return map;
}
Please try the given code below, hope it will helpful to you,
import java.util.Scanner;
class String55 {
public static int frequency(String s1,String s2)
{
int count=0;
char ch[]=s1.toCharArray();
char ch1[]=s2.toCharArray();
for (int i=0;i<ch.length-1; i++)
{
int k=i;
int j1=i+1;
int j=0;
int j11=j;
int j2=j+1;
{
while(k<ch.length && j11<ch1.length && ch[k]==ch1[j11])
{
k++;
j11++;
}
int l=k+j1;
int m=j11+j2;
if( l== m)
{
count=1;
count++;
}
}
}
return count;
}
public static void main (String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("enter the pattern");
String s1=sc.next();
System.out.println("enter the String");
String s2=sc.next();
int res=frequency(s1, s2);
System.out.println("FREQUENCY==" +res);
}
}
SAMPLE OUTPUT:
enter the pattern
man
enter the String
dhimanman
FREQUENCY==2
Thank-you.Happy coding.
package com.dipu.string;
import java.util.HashMap;
import java.util.Map;
public class RepetativeCharInString {
public static void main(String[] args) {
String data = "aaabbbcccdddffffrss";
char[] charArray = data.toCharArray();
Map<Character, Integer> map = new HashMap<>();
for (char c : charArray) {
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
} else {
map.put(c, 1);
}
}
System.out.println(map);
}
}
*import java.util.ArrayList;
import java.util.Collections;
public class Freq {
public static void main(String[] args) {
// TODO Auto-generated method stub
String temp="zsaaqaaaaaaaabbbbbcc";
List<String> temp1= new ArrayList<String> ();
ArrayList<Integer>freq=new ArrayList<Integer>();
for(int i=0;i<temp.length()-1;i++)
{
temp1.add(Character.toString(temp.charAt(i)));
}
Set<String> uniqset=new HashSet<String>(temp1);
for(String s:uniqset)
{
freq.add(Collections.frequency(temp1, s));
System.out.println(s+" -->>"+Collections.frequency(temp1, s));
}
}
}
------Output-------
a -->>10
b -->>5
c -->>1
q -->>1
s -->>1
z -->>1
Use collections frequency method to count frequency of char*
Uffh. Don't you think this is the simplest solution?
char inputChar = '|';
int freq = "|fd|fdfd|f dfd|fd".replaceAll("[^" + inputChar +"]", "").length();
System.out.println("freq " + freq);
We can use frequency method of Collections class for this.
Split the string into string array. Use HashSet to remove duplicates and check frequency of each object in HashSet using frequency method of Collections
void usingCollections(){
String input = "cuttack";
String [] stringArray = input.split("");
Set<String> s = new HashSet(Arrays.asList(stringArray));
for(String abc : s){
System.out.println (abc + ":"+Collections.frequency(Arrays.asList(stringArray),abc));
}
}
This is more Effective way to count frequency of characters in a string
public class demo {
public static void main(String[] args) {
String s = "babdcwertyuiuygf";
Map<Character, Integer> map = new TreeMap<>();
s.chars().forEach(e->map.put((char)e, map.getOrDefault((char)e, 0) + 1));
StringBuffer myValue = new StringBuffer();
String myMapKeyValue = "";
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
myMapKeyValue = Character.toString(entry.getKey()).concat(
Integer.toString(entry.getValue()));
myValue.append(myMapKeyValue);
}
System.out.println(myValue);
}
}
Another way using map merge method
Map<Character, Integer> map = new HashMap<>();
String s = "aasjjikkk";
for (int i = 0; i < s.length(); i++) {
map.merge(s.charAt(i), 1, (l, r) -> l + r);
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
public class FrequenceyOfCharacters {
public static void main(String[] args) {
System.out.println("Please enter the string to count each character frequencey: ");
Scanner sc=new Scanner(System.in);
String s =sc.nextLine();
String input = s.replaceAll("\\s",""); // To remove space.
frequenceyCount(input);
}
private static void frequenceyCount(String input) {
Map<Character,Integer> hashCount=new HashMap<>();
Character c;
for(int i=0; i<input.length();i++)
{
c =input.charAt(i);
if(hashCount.get(c)!=null){
hashCount.put(c, hashCount.get(c)+1);
}else{
hashCount.put(c, 1);
}
}
Iterator it = hashCount.entrySet().iterator();
System.out.println("char : frequency");
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
System.out.println(pairs.getKey() + " : " + pairs.getValue());
it.remove();
}
}
}
import java.io.FileInputStream;
import java.util.HashSet;
import java.util.Iterator;
public class CountFrequencyOfCharater {
public static void main(String args[]) throws Exception
{
HashSet hs=new HashSet();
String str="hey how are you?";
char arr[]=new char[str.length()];
for(int i=0;i<str.length();i++)
{
arr[i]=str.charAt(i);
}
for(int j=0;j<str.length();j++)
{
int c=0;
for(int k=0;k<str.length();k++)
{
if(arr[j]==arr[k])
c++;
}
hs.add(arr[j]+"="+c+",");
}
Iterator it=hs.iterator();
while(it.hasNext())
{
System.out.print(it.next());
}
}
}
#From C language
#include<stdio.h>`
#include <string.h>`
int main()
{
char s[1000];
int i,j,k,count=0,n;
printf("Enter the string : ");
gets(s);
for(j=0;s[j];j++);
n=j;
printf(" frequency count character in string:\n");
for(i=0;i<n;i++)
{
count=1;
if(s[i])
{
for(j=i+1;j<n;j++)
{
if(s[i]==s[j])
{
count++;
s[j]='\0';
}
}
printf(" '%c' = %d \n",s[i],count);
}
}
return 0;
}