Java How to print -1 if the given letter1 is not present - java

I would like to write a program that is taking letter position from two strings, string1 and string2, then it will check where in string2 we have the same letters used but also print number of indexes and if there is no letter that is in the first string just print -1 . For example I have first string = "reds" second one = "Hello world!", then my output should be:
r: 8, e: 1, d: 10, s: -1
Here is my code:
public static void main(String[] args){
String set1 = "reds";
String set2 = "Hello world!";
for(int i = 0; i < set1.length(); i++)
{
for(int j = 0; j < set2.length();j++)
{
char currentChar = set1.charAt(i);
char currentChar2 = set2.charAt(j);
if(currentChar == currentChar2)
{
System.out.println(currentChar+": "+j);
}
}
}
}
}

Another ways using String.indexOf
Classic for loop
String set1 = "reds";
String set2 = "Hello world!";
for(int i = 0; i < set1.length(); i++){
System.out.println(set1.charAt(i) + " : " + set2.indexOf(set1.charAt(i)));
}
or streams
set1.chars()
.mapToObj(c -> (char)c + " : " + set2.indexOf(c))
.forEach(System.out::println);
Note: if the chars apear more than once in the second string the first index of the chars is printed (use lastIndexOf if you want the last index)

public static void main(String[] args){
String set1 = "reds";
String set2 = "Hello world!";
for(int i = 0; i < set1.length(); i++) {
char currentChar = set1.charAt(i);
boolean found = false;
for(int j = 0; j < set2.length();j++) {
char currentChar2 = set2.charAt(j);
if(currentChar == currentChar2) {
System.out.println(currentChar+": "+j);
found = true;
}
}
if(!found) {
System.out.println(currentChar + ": -1");
}
}
}

It will print every position of the set1 characters into set2.
O(n + m) time complexity, where n and m are the sizes of set1 and set2
O(256) space complexity because of ASCII numbers
public static void main(String[] args){
String set1 = "reds";
String set2 = "Hello world!";
Map<Integer, List<Integer>> map = new HashMap<>(); // key = ascii value of the char, value = list of indexes
for(int i = 0; i < set2.length(); i++){
int key = set2.charAt(i);
if(!map.containsKey(key)){
map.put(key, new ArrayList<>());
}
List<Integer> indexesList = map.get(key);
indexesList.add(i);
map.put(key, indexesList);
}
for(int i = 0; i < set1.length(); i++){
int key = set1.charAt(i);
System.out.print(set1.charAt(i) + ": ");
if(!map.containsKey(key)){
System.out.println(-1);
}
else {
map.get(key).forEach(x-> System.out.print(x+ " "));
System.out.println(); // just for new line
}
}
}

Related

Java: Print a unique character in a string

I'm writing a program that will print the unique character in a string (entered through a scanner). I've created a method that tries to accomplish this but I keep getting characters that are not repeats, instead of a character (or characters) that is unique to the string. I want the unique letters only.
Here's my code:
import java.util.Scanner;
public class Sameness{
public static void main (String[]args){
Scanner kb = new Scanner (System.in);
String word = "";
System.out.println("Enter a word: ");
word = kb.nextLine();
uniqueCharacters(word);
}
public static void uniqueCharacters(String test){
String temp = "";
for (int i = 0; i < test.length(); i++){
if (temp.indexOf(test.charAt(i)) == - 1){
temp = temp + test.charAt(i);
}
}
System.out.println(temp + " ");
}
}
And here's sample output with the above code:
Enter a word:
nreena
nrea
The expected output would be: ra
Based on your desired output, you have to replace a character that initially has been already added when it has a duplicated later, so:
public static void uniqueCharacters(String test){
String temp = "";
for (int i = 0; i < test.length(); i++){
char current = test.charAt(i);
if (temp.indexOf(current) < 0){
temp = temp + current;
} else {
temp = temp.replace(String.valueOf(current), "");
}
}
System.out.println(temp + " ");
}
How about applying the KISS principle:
public static void uniqueCharacters(String test) {
System.out.println(test.chars().distinct().mapToObj(c -> String.valueOf((char)c)).collect(Collectors.joining()));
}
The accepted answer will not pass all the test case for example
input -"aaabcdd"
desired output-"bc"
but the accepted answer will give -abc
because the character a present odd number of times.
Here I have used ConcurrentHasMap to store character and the number of occurrences of character then removed the character if the occurrences is more than one time.
import java.util.concurrent.ConcurrentHashMap;
public class RemoveConductive {
public static void main(String[] args) {
String s="aabcddkkbghff";
String[] cvrtar=s.trim().split("");
ConcurrentHashMap<String,Integer> hm=new ConcurrentHashMap<>();
for(int i=0;i<cvrtar.length;i++){
if(!hm.containsKey(cvrtar[i])){
hm.put(cvrtar[i],1);
}
else{
hm.put(cvrtar[i],hm.get(cvrtar[i])+1);
}
}
for(String ele:hm.keySet()){
if(hm.get(ele)>1){
hm.remove(ele);
}
}
for(String key:hm.keySet()){
System.out.print(key);
}
}
}
Though to approach a solution I would suggest you to try and use a better data structure and not just string. Yet, you can simply modify your logic to delete already existing duplicates using an else as follows :
public static void uniqueCharacters(String test) {
String temp = "";
for (int i = 0; i < test.length(); i++) {
char ch = test.charAt(i);
if (temp.indexOf(ch) == -1) {
temp = temp + ch;
} else {
temp.replace(String.valueOf(ch),""); // added this to your existing code
}
}
System.out.println(temp + " ");
}
This is an interview question. Find Out all the unique characters of a string.
Here is the complete solution. The code itself is self explanatory.
public class Test12 {
public static void main(String[] args) {
String a = "ProtijayiGiniGina";
allunique(a);
}
private static void allunique(String a) {
int[] count = new int[256];// taking count of characters
for (int i = 0; i < a.length(); i++) {
char ch = a.charAt(i);
count[ch]++;
}
for (int i = 0; i < a.length(); i++) {
char chh = a.charAt(i);
// character which has arrived only one time in the string will be printed out
if (count[chh] == 1) {
System.out.println("index => " + i + " and unique character => " + a.charAt(i));
}
}
}// unique
}
In Python :
def firstUniqChar(a):
count = [0] *256
for i in a: count[ord(i)] += 1
element = ""
for item in a:
if (count[ord(item)] == 1):
element = item;
break;
return element
a = "GiniGinaProtijayi";
print(firstUniqChar(a)) # output is P
public static String input = "10 5 5 10 6 6 2 3 1 3 4 5 3";
public static void uniqueValue (String numbers) {
String [] str = input.split(" ");
Set <String> unique = new HashSet <String> (Arrays.asList(str));
System.out.println(unique);
for (String value:unique) {
int count = 0;
for ( int i= 0; i<str.length; i++) {
if (value.equals(str[i])) {
count++;
}
}
System.out.println(value+"\t"+count);
}
}
public static void main(String [] args) {
uniqueValue(input);
}
Step1: To find the unique characters in a string, I have first taken the string from user.
Step2: Converted the input string to charArray using built in function in java.
Step3: Considered two HashSet (set1 for storing all characters even if it is getting repeated, set2 for storing only unique characters.
Step4 : Run for loop over the array and check that if particular character is not there in set1 then add it to both set1 and set2. if that particular character is already there in set1 then add it to set1 again but remove it from set2.( This else part is useful when particular character is getting repeated odd number of times).
Step5 : Now set2 will have only unique characters. Hence, just print that set2.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String str = input.next();
char arr[] = str.toCharArray();
HashSet<Character> set1=new HashSet<Character>();
HashSet<Character> set2=new HashSet<Character>();
for(char i:arr)
{
if(set1.contains(i))
{
set1.add(i);
set2.remove(i);
}
else
{
set1.add(i);
set2.add(i);
}
}
System.out.println(set2);
}
I would store all the characters of the string in an array that you will loop through to check if the current characters appears there more than once. If it doesn't, then add it to temp.
public static void uniqueCharacters(String test) {
String temp = "";
char[] array = test.toCharArray();
int count; //keep track of how many times the character exists in the string
outerloop: for (int i = 0; i < test.length(); i++) {
count = 0; //reset the count for every new letter
for(int j = 0; j < array.length; j++) {
if(test.charAt(i) == array[j])
count++;
if(count == 2){
count = 0;
continue outerloop; //move on to the next letter in the string; this will skip the next two lines below
}
}
temp += test.charAt(i);
System.out.println("Adding.");
}
System.out.println(temp);
}
I have added comments for some more detail.
import java.util.*;
import java.lang.*;
class Demo
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter String");
String s1=sc.nextLine();
try{
HashSet<Object> h=new HashSet<Object>();
for(int i=0;i<s1.length();i++)
{
h.add(s1.charAt(i));
}
Iterator<Object> itr=h.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
catch(Exception e)
{
System.out.println("error");
}
}
}
If you don't want to use additional space:
String abc="developer";
System.out.println("The unique characters are-");
for(int i=0;i<abc.length();i++)
{
for(int j=i+1;j<abc.length();j++)
{
if(abc.charAt(i)==abc.charAt(j))
abc=abc.replace(String.valueOf(abc.charAt(j))," ");
}
}
System.out.println(abc);
Time complexity O(n^2) and no space.
This String algorithm is used to print unique characters in a string.It runs in O(n) runtime where n is the length of the string.It supports ASCII characters only.
static String printUniqChar(String s) {
StringBuilder buildUniq = new StringBuilder();
boolean[] uniqCheck = new boolean[128];
for (int i = 0; i < s.length(); i++) {
if (!uniqCheck[s.charAt(i)]) {
uniqCheck[s.charAt(i)] = true;
if (uniqCheck[s.charAt(i)])
buildUniq.append(s.charAt(i));
}
}
public class UniqueCharactersInString {
public static void main(String []args){
String input = "aabbcc";
String output = uniqueString(input);
System.out.println(output);
}
public static String uniqueString(String s){
HashSet<Character> uniques = new HashSet<>();
uniques.add(s.charAt(0));
String out = "";
out += s.charAt(0);
for(int i =1; i < s.length(); i++){
if(!uniques.contains(s.charAt(i))){
uniques.add(s.charAt(i));
out += s.charAt(i);
}
}
return out;
}
}
What would be the inneficiencies of this answer? How does it compare to other answers?
Based on your desired output you can replace each character already present with a blank character.
public static void uniqueCharacters(String test){
String temp = "";
for(int i = 0; i < test.length(); i++){
if (temp.indexOf(test.charAt(i)) == - 1){
temp = temp + test.charAt(i);
} else {
temp.replace(String.valueOf(temp.charAt(i)), "");
}
}
System.out.println(temp + " ");
}
public void uniq(String inputString) {
String result = "";
int inputStringLen = inputStr.length();
int[] repeatedCharacters = new int[inputStringLen];
char inputTmpChar;
char tmpChar;
for (int i = 0; i < inputStringLen; i++) {
inputTmpChar = inputStr.charAt(i);
for (int j = 0; j < inputStringLen; j++) {
tmpChar = inputStr.charAt(j);
if (inputTmpChar == tmpChar)
repeatedCharacters[i]++;
}
}
for (int k = 0; k < inputStringLen; k++) {
inputTmpChar = inputStr.charAt(k);
if (repeatedCharacters[k] == 1)
result = result + inputTmpChar + " ";
}
System.out.println ("Unique characters: " + result);
}
In first for loop I count the number of times the character repeats in the string. In the second line I am looking for characters repetitive once.
how about this :)
for (int i=0; i< input.length();i++)
if(input.indexOf(input.charAt(i)) == input.lastIndexOf(input.charAt(i)))
System.out.println(input.charAt(i) + " is unique");
package extra;
public class TempClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
String abcString="hsfj'pwue2hsu38bf74sa';fwe'rwe34hrfafnosdfoasq7433qweid";
char[] myCharArray=abcString.toCharArray();
TempClass mClass=new TempClass();
mClass.countUnique(myCharArray);
mClass.countEach(myCharArray);
}
/**
* This is the program to find unique characters in array.
* #add This is nice.
* */
public void countUnique(char[] myCharArray) {
int arrayLength=myCharArray.length;
System.out.println("Array Length is: "+arrayLength);
char[] uniqueValues=new char[myCharArray.length];
int uniqueValueIndex=0;
int count=0;
for(int i=0;i<arrayLength;i++) {
for(int j=0;j<arrayLength;j++) {
if (myCharArray[i]==myCharArray[j] && i!=j) {
count=count+1;
}
}
if (count==0) {
uniqueValues[uniqueValueIndex]=myCharArray[i];
uniqueValueIndex=uniqueValueIndex+1;
count=0;
}
count=0;
}
for(char a:uniqueValues) {
System.out.println(a);
}
}
/**
* This is the program to find count each characters in array.
* #add This is nice.
* */
public void countEach(char[] myCharArray) {
}
}
Here str will be your string to find the unique characters.
function getUniqueChars(str){
let uniqueChars = '';
for(let i = 0; i< str.length; i++){
for(let j= 0; j< str.length; j++) {
if(str.indexOf(str[i]) === str.lastIndexOf(str[j])) {
uniqueChars += str[i];
}
}
}
return uniqueChars;
}
public static void main(String[] args) {
String s = "aaabcdd";
char a[] = s.toCharArray();
List duplicates = new ArrayList();
List uniqueElements = new ArrayList();
for (int i = 0; i < a.length; i++) {
uniqueElements.add(a[i]);
for (int j = i + 1; j < a.length; j++) {
if (a[i] == a[j]) {
duplicates.add(a[i]);
break;
}
}
}
uniqueElements.removeAll(duplicates);
System.out.println(uniqueElements);
System.out.println("First Unique : "+uniqueElements.get(0));
}
Output :
[b, c]
First Unique : b
import java.util.*;
public class Sameness{
public static void main (String[]args){
Scanner kb = new Scanner (System.in);
String word = "";
System.out.println("Enter a word: ");
word = kb.nextLine();
uniqueCharacters(word);
}
public static void uniqueCharacters(String test){
for(int i=0;i<test.length();i++){
if(test.lastIndexOf(test.charAt(i))!=i)
test=test.replaceAll(String.valueOf(test.charAt(i)),"");
}
System.out.println(test);
}
}
public class Program02
{
public static void main(String[] args)
{
String inputString = "abhilasha";
for (int i = 0; i < inputString.length(); i++)
{
for (int j = i + 1; j < inputString.length(); j++)
{
if(inputString.toCharArray()[i] == inputString.toCharArray()[j])
{
inputString = inputString.replace(String.valueOf(inputString.charAt(j)), "");
}
}
}
System.out.println(inputString);
}
}

how to extract longest sub string (having distinct consecutive character) from a string in java

I want to extract longest distinct consecutive substring from a string
for eg:
1 )abcdeddd
should give
abcde
2) aaabcdrrr
abcd
i wrote this code
for (int i = 0; i < lines; i++) {
String s = bf.readLine();
ArrayList<String> al = new ArrayList<String>();
TreeMap<Integer, Integer> count = new TreeMap<Integer, Integer>();
int point = 0;
for (int j = 0; j < s.length() - 1; j++) {
if (s.charAt(j + 1) != s.charAt(j)) {
Character xyz = s.charAt(j);
String news = al.get(point).concat(xyz.toString());
al.add(point, news);
} else if (s.charAt(j + 1) == s.charAt(j)) {
point++;
}
for (int k = 0; k < al.size(); k++) {
count.put(al.get(k).length(), k);
}
System.out.println(al.get(count.get(count.size() - 1)));
}
}
} catch (Exception e) {
}
}
You can try this way too.
String s = "abcdefgdrrstqrstuvwxyzprr";
Map<Integer,String> results=new HashMap<>();
Set<String> set=new LinkedHashSet<>();
for(int i=0;i<s.length()-1;i++){
if(s.charAt(i)-s.charAt(i+1)==-1){
set.add(""+s.charAt(i));
set.add(""+s.charAt(i+1));
}else {
results.put(set.size(), set.toString());
set=new LinkedHashSet<>();
}
}
System.out.println(results);
Out put:
{0=[], 3=[r, s, t], 7=[a, b, c, d, e, f, g], 10=[q, r, s, t, u, v, w, x, y, z]}
Now you can see all consecutive chars. and answer is largest one. In this way you can find more than one consecutive substring if they are in same length.
You can get it
String largest=new ArrayList<>(results.values())
.get(results.size()-1).replaceAll("\\[|]|, ","");
if("".equals(largest)){
System.out.println("There is not consecutive substring for \""+s+"\"");
}else {
System.out.println("largest consecutive substring of \""+s+"\" is "+ largest);
}
Now out put:
largest consecutive substring of "abcdefgdrrstqrstuvwxyzprr" is qrstuvwxyz
You can iterate/check each of the character starting from character x where x is the starting point of the character checking, then increment to check if the next index of character is corresponds to the next alphabet from the last character.
sample:
String s = "abcdefgdrrstqrstuvwxyzprr";
int start = s.charAt(0);
StringBuilder temp = new StringBuilder();
String temp2 = "";
boolean done = false;
for(int i = 0; i < s.toCharArray().length; i++)
{
if(s.toCharArray()[i] == start) {
temp.append(s.toCharArray()[i]);
start++;
done = true;
if(i == s.toCharArray().length-1)
temp2 = !(temp2.length() > temp.length()) ? temp.toString() : temp2;
}else
{
if(done)
{
if(!(temp2.length() > temp.length()))
temp2 = temp.toString();
--i;
}
temp = new StringBuilder("");
done = false;
start = (i == s.toCharArray().length-1) ? 0 : s.toCharArray()[i+1];
}
}
System.out.println("LONGEST IS: " + temp2);
result:
qrstuvwxyz
And if the test String is abcdeddd the result would be abcde
Here is my solution:
String input = "abcdabcdeabcedeabcdefffff";
String longest = "";
String temp = "";
for(int pos=0; pos<input.length(); pos++) {
if(temp.isEmpty()) {
temp = String.valueOf(input.charAt(pos));
} else if(input.charAt(pos) == temp.charAt(temp.length() - 1) + 1) {
temp += input.charAt(pos);
} else {
temp = String.valueOf(input.charAt(pos));
}
if(temp.length() > longest.length())
longest = temp;
}
System.out.println(longest);
You could also use a StringBuilder for temp as it is more efficient for building Strings in Java.

Counting words from array in a string

I have an array of string say
A=["hello", "you"]
I have a string, say
s="hello, hello you are so wonderful"
I need to count the number of occurrence of strings from A in s.
In this case, the number of occurrences is 3 (2 "hello", 1 "you").
How to do this effectively? (A might contains lots of words, and s might be long in practice)
Try:
Map<String, Integer> wordCount = new HashMap<>();
for(String a : dictionnary) {
wordCount.put(a, 0);
}
for(String s : text.split("\\s+")) {
Integer count = wordCount.get(s);
if(count != null) {
wordCount.put(s, count + 1);
}
}
public void countMatches() {
String[] A = {"hello", "you"};
String s = "hello, hello you are so wonderful";
String patternString = "(" + StringUtils.join(A, "|") + ")";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(s);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println(count);
}
Note that StringUtils is from apache commons. If you don't want to include and additional jar you can just construct that string using a for loop.
HashSet<String> searchWords = new HashSet<String>();
for(String a : dictionary) {
searchWords.add(a);
}
int count = 0;
for(String s : input.split("[ ,]")) {
if(searchWords.contains(s)) {
count++;
}
}
int count =0;
for(int i=0;i<A.length;i++)
{
count = count + s.split(A[i],-1).length - 1;
}
Working Ideone : http://ideone.com/Z9K3JX
This is fully working method with output :)
public static void main(String[] args) {
String[] A={"hello", "you"};
String s= "hello, hello you are so wonderful";
int[] count = new int[A.length];
for (int i = 0; i < A.length; i++) {
count[i] = (s.length() - s.replaceAll(A[i], "").length())/A[i].length();
}
for (int i = 0; i < count.length; i++) {
System.out.println(A[i] + ": " + count[i]);
}
}
What does this line do?
count[i] = (s.length() - s.replaceAll(A[i], "").length())/A[i].length();
This part s.replaceAll(A[i], "") changes all "hello" to empty "" string in the text.
So I take the length of everything s.length() I substract from it the length of same string without that word s.replaceAll(A[i], "").length() and I divide it by the length of that word /A[i].length()
Sample output for this example :
hello: 2
you: 1
You can use the String Tokenizer
Do something like this:
A = ["hello", "you"];
s = "hello, hello you are so wonderful";
StringTokenizer st = new StringTokenizer(s);
while (st.hasMoreElements()) {
for (String i: A) {
if(st.nextToken() == i){
//You can keep going from here
}
}
}
This is what I came up with:
It doesn't create any new objects. It uses String.indexOf(String, int), keeps track of the current index, and increments the occurance-count.
public class SearchWordCount {
public static final void main(String[] ignored) {
String[] searchWords = {"hello", "you"};
String input = "hello, hello you are so wonderful";
for(int i = 0; i < searchWords.length; i++) {
String searchWord = searchWords[i];
System.out.print(searchWord + ": ");
int foundCount = 0;
int currIdx = 0;
while(currIdx != -1) {
currIdx = input.indexOf(searchWord, currIdx);
if(currIdx != -1) {
foundCount++;
currIdx += searchWord.length();
} else {
currIdx = -1;
}
}
System.out.println(foundCount);
}
}
}
Output:
hello: 2
you: 1

comparing string arrays in java

I am working on a simple Java program where we have sorted string array named arr
I am trying to compare two adjacent string and calculate frequency for each string present in that array
for(j1=0;j1<arr.length;j1++){
if(j1+1 < arr.length){ // To prevent arrayOutofBoundsException
if(arr[j1].equals(arr[j1+1])){
counter++;
}
else {
System.out.println(arr[j1]+" "+counter);
counter=1;
}
But it's not working right , what's wrong ?
edit:problem is not in comparing , it's not calculating frequency as desired
OK, besides the equals fix, you want to keep the original order of words:
String orig = "hellow hello hello how how he ho" ;
//String orig = "how are you how do you do";
String[] arr = orig.split(" ");
//Arrays.sort(arr);
for(int j1 = 0; j1 < arr.length; j1++){
if (arr[j1] != null) {
int counter = 1;
for(int j2 = j1+1; j2 < arr.length; j2++) {
if(arr[j2] != null && arr[j1].equals(arr[j2])){
counter++;
arr[j2] = null;
}
}
System.out.println(arr[j1]+" "+counter);
}
}
The trick is that I run through the array, count all occurrences, null the occurrences, so they don't count again, and print the count. No need to sort the array.
== compares object identity in terms of memory address - to compare objects in terms of equality, use the equals-method.
This should work:
public static void main(String[] args)
{
String text = "how are you how do you do";
String[] keys = {"how", "are", "you", "how", "do", "you", "do"};
Arrays.sort(keys);
String[] uniqueKeys;
int count = 0;
System.out.println(text);
uniqueKeys = getUniqueKeys(keys);
for(String key: uniqueKeys)
{
if(null == key)
{
break;
}
for(String s : keys)
{
if(key.equals(s))
{
count++;
}
}
System.out.println("Count of ["+key+"] is : "+count);
count=0;
}
}
private static String[] getUniqueKeys(String[] keys)
{
String[] uniqueKeys = new String[keys.length];
uniqueKeys[0] = keys[0];
int uniqueKeyIndex = 1;
boolean keyAlreadyExists = false;
for(int i=1; i<keys.length ; i++)
{
for(int j=0; j<=uniqueKeyIndex; j++)
{
if(keys[i].equals(uniqueKeys[j]))
{
keyAlreadyExists = true;
}
}
if(!keyAlreadyExists)
{
uniqueKeys[uniqueKeyIndex] = keys[i];
uniqueKeyIndex++;
}
keyAlreadyExists = false;
}
return uniqueKeys;
}
Output:
how are you how do you do
Count of [how] is : 2
Count of [are] is : 1
Count of [you] is : 2
Count of [do] is : 2
Are you looking some sort of this
public static void main(String[] args){
String[] arr = new String[5];
arr[0] = "One";
arr[1] = "Two";
arr[2] = "One";
arr[3] = "Three";
arr[4] = "Two";
List<String> lstString = Arrays.asList(arr);
Collections.sort(lstString);
for(String eachString : arr){
System.out.println("Frequency of " + eachString + " is " + getFrequency(eachString,lstString));
}
}
private static int getFrequency(String word, List lstOfString){
int frequency = 1;
if(lstOfString != null && lstOfString.size() > 0){
int firstIndex = lstOfString.indexOf(word);
int lastIndex = lstOfString.lastIndexOf(word);
frequency += lastIndex - firstIndex;
}
return frequency;
}
Result :
Frequency of One is 2
Frequency of One is 2
Frequency of Three is 1
Frequency of Two is 2
Frequency of Two is 2

Find duplicate characters in a String and count the number of occurrences using Java

How can I find the number of occurrences of a character in a string?
For example: The quick brown fox jumped over the lazy dog.
Some example outputs are below,
'a' = 1
'o' = 4
'space' = 8
'.' = 1
You could use the following, provided String s is the string you want to process.
Map<Character,Integer> map = new HashMap<Character,Integer>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (map.containsKey(c)) {
int cnt = map.get(c);
map.put(c, ++cnt);
} else {
map.put(c, 1);
}
}
Note, it will count all of the chars, not only letters.
Java 8 way:
"The quick brown fox jumped over the lazy dog."
.chars()
.mapToObj(i -> (char) i)
.collect(Collectors.groupingBy(Object::toString, Collectors.counting()));
void Findrepeter(){
String s="mmababctamantlslmag";
int distinct = 0 ;
for (int i = 0; i < s.length(); i++) {
for (int j = 0; j < s.length(); j++) {
if(s.charAt(i)==s.charAt(j))
{
distinct++;
}
}
System.out.println(s.charAt(i)+"--"+distinct);
String d=String.valueOf(s.charAt(i)).trim();
s=s.replaceAll(d,"");
distinct = 0;
}
}
import java.io.*;
public class CountChar
{
public static void main(String[] args) throws IOException
{
String ch;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the Statement:");
ch=br.readLine();
int count=0,len=0;
do
{
try
{
char name[]=ch.toCharArray();
len=name.length;
count=0;
for(int j=0;j<len;j++)
{
if((name[0]==name[j])&&((name[0]>=65&&name[0]<=91)||(name[0]>=97&&name[0]<=123)))
count++;
}
if(count!=0)
System.out.println(name[0]+" "+count+" Times");
ch=ch.replace(""+name[0],"");
}
catch(Exception ex){}
}
while(len!=1);
}
}
Output
Enter the Statement:asdf23123sfsdf
a 1 Times
s 3 Times
d 2 Times
f 3 Times
A better way would be to create a Map to store your count. That would be a Map<Character, Integer>
You need iterate over each character of your string, and check whether its an alphabet. You can use Character#isAlphabetic method for that. If it is an alphabet, increase its count in the Map. If the character is not already in the Map then add it with a count of 1.
NOTE: - Character.isAlphabetic method is new in Java 7. If you are using an older version, you should use Character#isLetter
String str = "asdfasdfafk asd234asda";
Map<Character, Integer> charMap = new HashMap<Character, Integer>();
char[] arr = str.toCharArray();
for (char value: arr) {
if (Character.isAlphabetic(value)) {
if (charMap.containsKey(value)) {
charMap.put(value, charMap.get(value) + 1);
} else {
charMap.put(value, 1);
}
}
}
System.out.println(charMap);
OUTPUT: -
{f=3, d=4, s=4, a=6, k=1}
If your string only contains alphabets then you can use some thing like this.
public class StringExample {
public static void main(String[] args) {
String str = "abcdabghplhhnfl".toLowerCase();
// create a integer array for 26 alphabets.
// where index 0,1,2.. will be the container for frequency of a,b,c...
Integer[] ar = new Integer[26];
// fill the integer array with character frequency.
for(int i=0;i<str.length();i++) {
int j = str.charAt(i) -'a';
if(ar[j]==null) {
ar[j]= 1;
}else {
ar[j]+= 1;
}
}
// print only those alphabets having frequency greater then 1.
for(int i=0;i<ar.length;i++) {
if(ar[i]!=null && ar[i]>1) {
char c = (char) (97+i);
System.out.println("'"+c+"' comes "+ar[i]+" times.");
}
}
}
}
Output:
'a' comes 2 times.
'b' comes 2 times.
'h' comes 3 times.
'l' comes 2 times.
Finding the duplicates in a String:
Example 1 : Using HashMap
public class a36 {
public static void main(String[] args) {
String a = "Gini Rani";
fix(a);
}//main
public static void fix(String a ){
Map<Character ,Integer> map = new HashMap<>();
for (int i = 0; i <a.length() ; i++ ) {
char ch = a.charAt(i);
map.put(ch , map.getOrDefault(ch,0) +1 );
}//for
List<Character> list = new ArrayList<>();
Set<Map.Entry<Character ,Integer> > entrySet = map.entrySet();
for ( Map.Entry<Character ,Integer> entry : entrySet) {
list.add( entry.getKey() );
System.out.printf( " %s : %d %n" , entry.getKey(), entry.getValue() );
}//for
System.out.println("Duplicate elements => " + list);
}//fix
}
Example 2 : using Arrays.stream() in Java 8
public class a37 {
public static void main(String[] args) {
String aa = "Protijayi Gini";
String[] stringarray = aa.split("");
Map<String , Long> map = Arrays.stream(stringarray)
.collect(Collectors.groupingBy(c -> c , Collectors.counting()));
map.forEach( (k, v) -> System.out.println(k + " : "+ v) );
}
}
This is the implementation without using any Collection and with complexity order of n. Although the accepted solution is good enough and does not use Collection as well but it seems, it is not taking care of special characters.
import java.util.Arrays;
public class DuplicateCharactersInString {
public static void main(String[] args) {
String string = "check duplicate charcters in string";
string = string.toLowerCase();
char[] charAr = string.toCharArray();
Arrays.sort(charAr);
for (int i = 1; i < charAr.length;) {
int count = recursiveMethod(charAr, i, 1);
if (count > 1) {
System.out.println("'" + charAr[i] + "' comes " + count + " times");
i = i + count;
} else
i++;
}
}
public static int recursiveMethod(char[] charAr, int i, int count) {
if (ifEquals(charAr[i - 1], charAr[i])) {
count = count + recursiveMethod(charAr, ++i, count);
}
return count;
}
public static boolean ifEquals(char a, char b) {
return a == b;
}
}
Output :
' ' comes 4 times
'a' comes 2 times
'c' comes 5 times
'e' comes 3 times
'h' comes 2 times
'i' comes 3 times
'n' comes 2 times
'r' comes 3 times
's' comes 2 times
't' comes 3 times
public class dublicate
{
public static void main(String...a)
{
System.out.print("Enter the String");
Scanner sc=new Scanner(System.in);
String st=sc.nextLine();
int [] ar=new int[256];
for(int i=0;i<st.length();i++)
{
ar[st.charAt(i)]=ar[st.charAt(i)]+1;
}
for(int i=0;i<256;i++)
{
char ch=(char)i;
if(ar[i]>0)
{
if(ar[i]==1)
{
System.out.print(ch);
}
else
{
System.out.print(ch+""+ar[i]);
}
}
}
}
}
Use google guava Multiset<String>.
Multiset<String> wordsMultiset = HashMultiset.create();
wordsMultiset.addAll(words);
for(Multiset.Entry<E> entry:wordsMultiset.entrySet()){
System.out.println(entry.getElement()+" - "+entry.getCount());
}
public static void main(String args[]) {
char Char;
int count;
String a = "Hi my name is Rahul";
a = a.toLowerCase();
for (Char = 'a'; Char <= 'z'; Char++) {
count = 0;
for (int i = 0; i < a.length(); i++) {
if (a.charAt(i) == Char) {
count++;
}
}
System.out.println("Number of occurences of " + Char + " is " + count);
}
}
public static void main(String[] args) {
String name="AnuvratAnuvra";
char[] arr = name.toCharArray();
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
for(char val:arr){
map.put(val,map.containsKey(val)?map.get(val)+1:1);
}
for (Entry<Character, Integer> entry : map.entrySet()) {
if(entry.getValue()>1){
Character key = entry.getKey();
Object value = entry.getValue();
System.out.println(key + ":"+value);
}
}
}
class A {
public static void getDuplicates(String S) {
int count = 0;
String t = "";
for (int i = 0; i < S.length() - 1; i++) {
for (int j = i + 1; j < S.length(); j++) {
if (S.charAt(i) == S.charAt(j) && !t.contains(S.charAt(j) + "")) {
t = t + S.charAt(i);
}
}
}
System.out.println(t);
}
}
class B
public class B {
public static void main(String[] args){
A.getDuplicates("mymgsgkkabcdyy");
}
}
You can also achieve it by iterating over your String and using a switch to check each individual character, adding a counter whenever it finds a match. Ah, maybe some code will make it clearer:
Main Application:
public static void main(String[] args) {
String test = "The quick brown fox jumped over the lazy dog.";
int countA = 0, countO = 0, countSpace = 0, countDot = 0;
for (int i = 0; i < test.length(); i++) {
switch (test.charAt(i)) {
case 'a':
case 'A': countA++; break;
case 'o':
case 'O': countO++; break;
case ' ': countSpace++; break;
case '.': countDot++; break;
}
}
System.out.printf("%s%d%n%s%d%n%s%d%n%s%d", "A: ", countA, "O: ", countO, "Space: ", countSpace, "Dot: ", countDot);
}
Output:
A: 1
O: 4
Space: 8
Dot: 1
import java.util.HashMap;
import java.util.Scanner;
public class HashMapDemo {
public static void main(String[] args) {
//Create HashMap object to Store Element as Key and Value
HashMap<Character,Integer> hm= new HashMap<Character,Integer>();
//Enter Your String From Console
System.out.println("Enter an String:");
//Create Scanner Class Object From Retrive the element from console to our java application
Scanner sc = new Scanner(System.in);
//Store Data in an string format
String s1=sc.nextLine();
//find the length of an string and check that hashmap object contain the character or not by using
//containskey() if that map object contain element only one than count that value as one or if it contain more than one than increment value
for(int i=0;i<s1.length();i++){
if(!hm.containsKey(s1.charAt(i))){
hm.put(s1.charAt(i),(Integer)1);
}//if
else{
hm.put(s1.charAt(i),hm.get(s1.charAt(i))+1);
}//else
}//for
System.out.println("The Charecters are:"+hm);
}//main
}//HashMapDemo
There are three ways to find duplicates
public class WAP_PrintDuplicates {
public static void main(String[] args) {
String input = "iabccdeffghhijkkkl";
findDuplicate1(input);
findDuplicate2(input);
findDuplicate3(input);
}
private static void findDuplicate3(String input) {
HashMap<Character, Integer> hm = new HashMap<Character, Integer>();
for (int i = 0; i < input.length() - 1; i++) {
int ch = input.charAt(i);
if (hm.containsKey(input.charAt(i))) {
int value = hm.get(input.charAt(i));
hm.put(input.charAt(i), value + 1);
} else {
hm.put(input.charAt(i), 1);
}
}
Set<Entry<Character, Integer>> entryObj = hm.entrySet();
for (Entry<Character, Integer> entry : entryObj) {
if (entry.getValue() > 1) {
System.out.println("Duplicate: " + entry.getKey());
}
}
}
private static void findDuplicate2(String input) {
int i = 0;
for (int j = i + 1; j < input.length(); j++, i++) {
if (input.charAt(i) == input.charAt(j)) {
System.out.println("Duplicate is: " + input.charAt(i));
}
}
}
private static void findDuplicate1(String input) {
// TODO Auto-generated method stub
for (int i = 0; i < input.length(); i++) {
for (int j = i + 1; j < input.length(); j++) {
if (input.charAt(i) == input.charAt(j)) {
System.out.println("Duplicate is: " + input.charAt(i));
}
}
}
}
}
Using Eclipse Collections CharAdapter and CharBag:
CharBag bag =
Strings.asChars("The quick brown fox jumped over the lazy dog.").toBag();
Assert.assertEquals(1, bag.occurrencesOf('a'));
Assert.assertEquals(4, bag.occurrencesOf('o'));
Assert.assertEquals(8, bag.occurrencesOf(' '));
Assert.assertEquals(1, bag.occurrencesOf('.'));
Note: I am a committer for Eclipse Collections
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class DuplicateCountChar{
public static void main(String[] args) {
Scanner inputString = new Scanner(System.in);
String token = inputString.nextLine();
char[] ch = token.toCharArray();
Map<Character, Integer> dupCountMap = new HashMap<Character,Integer>();
for (char c : ch) {
if(dupCountMap.containsKey(c)) {
dupCountMap.put(c, dupCountMap.get(c)+1);
}else {
dupCountMap.put(c, 1);
}
}
for (char c : ch) {
System.out.println("Key = "+c+ "Value : "+dupCountMap.get(c));
}
Set<Character> keys = dupCountMap.keySet();
for (Character character : keys) {
System.out.println("Key = "+character+ " Value : " + dupCountMap.get(character));
}
}**
In java... using for loop:
import java.util.Scanner;
/**
*
* #author MD SADDAM HUSSAIN */
public class Learn {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String input = sc.next();
char process[] = input.toCharArray();
boolean status = false;
int index = 0;
for (int i = 0; i < process.length; i++) {
for (int j = 0; j < process.length; j++) {
if (i == j) {
continue;
} else {
if (process[i] == process[j]) {
status = true;
index = i;
break;
} else {
status = false;
}
}
}
if (status) {
System.out.print("" + process[index]);
}
}
}
}
public class StringCountwithOutHashMap {
public static void main(String[] args) {
System.out.println("Plz Enter Your String: ");
Scanner sc = new Scanner(System.in);
String s1 = sc.nextLine();
int count = 0;
for (int i = 0; i < s1.length(); i++) {
for (int j = 0; j < s1.length(); j++) {
if (s1.charAt(i) == s1.charAt(j)) {
count++;
}
}
System.out.println(s1.charAt(i) + " --> " + count);
String d = String.valueOf(s1.charAt(i)).trim();
s1 = s1.replaceAll(d, "");
count = 0;
}}}
public class CountH {
public static void main(String[] args) {
String input = "Hi how are you";
char charCount = 'h';
int count = 0;
input = input.toLowerCase();
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == charCount) {
count++;
}
}
System.out.println(count);
}
}
public class DuplicateValue {
public static void main(String[] args) {
String s = "hezzz";
char []st=s.toCharArray();
int count=0;
Set<Character> ch=new HashSet<>();
for(Character cg:st){
if(ch.add(cg)==false){
int occurrences = Collections.frequency(ch, cg);
count+=occurrences;
if(count>1){
System.out.println(cg + ": This character exist more than one time");
}
else{
System.out.println(cg);
}
}
}
System.out.println(count);
}
}
Map<Character,Integer> listMap = new HashMap<Character,Integer>();
Scanner in= new Scanner(System.in);
System.out.println("enter the string");
String name=in.nextLine().toString();
Integer value=0;
for(int i=0;i<name.length();i++){
if(i==0){
listMap.put(name.charAt(0), 1);
}
else if(listMap.containsKey(name.charAt(i))){
value=listMap.get(name.charAt(i));
listMap.put(name.charAt(i), value+1);
}else listMap.put(name.charAt(i),1);
}
System.out.println(listMap);
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String reverse1;
String reverse2;
int count = 0;
while(n > 0)
{
String A = sc.next();
String B = sc.next();
reverse1 = new StringBuffer(A).reverse().toString();
reverse2 = new StringBuffer(B).reverse().toString();
if(!A.equals(reverse1))
{
for(int i = 0; i < A.length(); i++)
{
for(int j = 0; j < A.length(); j++)
{
if(A.charAt(j) == A.charAt(i))
{
count++;
}
}
if(count % 2 != 0)
{
A.replace(A.charAt(i),"");
count = 0;
}
}
System.out.println(A);
}
n--;
}
}
}
public class list {
public static String name(Character k){
String s="the quick brown fox jumped over the lazy dog.";
int count=0;
String l1="";
String l="";
List<Character> list=new ArrayList<Character>();
for(int i1=0;i1<s.length();i1++){
list.add(s.charAt(i1));
}
list.sort(null);
for (Character character : list) {
l+=character;
}
for (int i1=0;i1<l.length();i1++) {
if((l.charAt(i1)==k)){
count+=1;
l1=l.charAt(i1)+" "+Integer.toString(count);
if(k==' '){
l1="Space"+" "+Integer.toString(count);
}
}else{
count=0;
}
}
return l1;
}
public static void main(String[] args){
String g = name('.');
System.out.println(g);
}
}
Simple and Easy way to find char occurrences >
void findOccurrences() {
String s = "The quick brown fox jumped over the lazy dog.";
Map<String, Integer> occurrences = new LinkedHashMap<String, Integer>();
for (String ch : s.split("")) {
Integer count = occurrences.get(ch);
occurrences.put(ch, count == null ? 1 : count + 1);
}
System.out.println(occurrences);
}
This will print output as:
{T=1, h=2, e=4, =8, q=1, u=2, i=1, c=1, k=1, b=1, r=2, o=4, w=1, n=1, f=1, x=1, j=1, m=1, p=1, d=2, v=1, t=1, l=1, a=1, z=1, y=1, g=1, .=1}
String str = "anand";
Map<Character, Integer> map
= new HashMap<Character, Integer>();
// Converting string into a char array
char[] charArray = str.toCharArray();
for (char c : charArray) {
if (map.containsKey(c)) {
// If character is present increment count by 1
map.put(c, map.get(c) + 1);
}
else {
// If character is not present
//putting this character into map with 1 as it's value.
map.put(c, 1);
}
}
for (Map.Entry<Character, Integer> entry :
map.entrySet()) {
System.out.println(entry.getKey()
+ " : "
+ entry.getValue());
}
Output:
a:2 n:2 d:1
Use the below code snippet
import java.util.HashMap;
import java.util.Map;
public class CountDuplicateChar {
public static void main(String... strings) {
withSortedString("aaaaabbcccccc");
withUnSortedString("aaaaab bcc *#ccccf");
withHashMap("bala");
}
private static void withHashMap(String inputString) {
Map<Character, Integer> map = new HashMap<>();
char[] charArray = inputString.toCharArray();
for (int i = 0 ; i < charArray.length ; i++ ){
if (map.containsKey(charArray[i])) {
map.put(charArray[i], map.get(charArray[i]) +1);
} else {
map.put(charArray[i], 1);
}
}
System.out.println(map);
}
private static void withUnSortedString(String unSortedString) {
int len = 0;
do {
char[] ch = unSortedString.toCharArray();
if (ch.length ==0)
break;
int count = 0 ;
for ( int i = 0 ; i < ch.length; i++) {
if (ch[0] == ch[i]) {
count++;
}
}
System.out.println(ch[0] + " - " + count + "times");
unSortedString = unSortedString.replace(""+ch[0],"");
}while (len!=1);
}
private static void withSortedString(String s) {
for(int i=0; i<s.length(); i++)
{
System.out.print(s.charAt(i)+""+(s.lastIndexOf(s.charAt(i))-s.indexOf(s.charAt(i))+1));
i = s.lastIndexOf(s.charAt(i));
}
System.out.println(" ");
}
}
Using Java 8 streams with groupingBy()
//way 1
String name = "anandha";
Map<Character,Long> map = name.chars()
.mapToObj(ch -> (char)ch)
.collect(Collectors.groupingBy(ch -> ch, Collectors.counting());
System.out.println(map);
using LinkedHashmap
//way2
String name = "anandha";
char[] charArray = name.toChararray();
Map<Character,Integer> map = new LinkedHashmap<>();
for(char ch: charArray)
{
if(map.containsKey(ch))
{
map.put(ch,map.get(ch)+1);
}else
{
map.put(ch,1)
}
}
map.foreach((key,value)->{
{
System.out.println(key +" : "+ value);
}
});
//(OR) iterate map using the way above or below
for(Map.Entry mp: map.entrySet())
{
System.out.println(mp.getKey()+" : "+ mp.getValue());
}
}
public static void main(String[] args) {
char[] array = "aabsbdcbdgratsbdbcfdgs".toCharArray();
char[][] countArr = new char[array.length][2];
int lastIndex = 0;
for (char c : array) {
int foundIndex = -1;
for (int i = 0; i < lastIndex; i++) {
if (countArr[i][0] == c) {
foundIndex = i;
break;
}
}
if (foundIndex >= 0) {
int a = countArr[foundIndex][1];
countArr[foundIndex][1] = (char) ++a;
} else {
countArr[lastIndex][0] = c;
countArr[lastIndex][1] = '1';
lastIndex++;
}
}
for (int i = 0; i < lastIndex; i++) {
System.out.println(countArr[i][0] + " " + countArr[i][1]);
}
}

Categories

Resources