I am trying to count the amount of times a word is repeated in stdin.
Example input:
This is a test, this is is
Desired output:
this 2
is 3
a 1
test 1
I have an int[] to store the wordCount but I'm not sure where to use it, the int count is just temporary so the program can run.
Here is my code for reference:
import java.util.Scanner;
public class WCount {
public static void main (String[] args) {
Scanner stdin = new Scanner(System.in);
String [] wordArray = new String [10000];
int [] wordCount = new int [10000];
int numWords = 0;
while(stdin.hasNextLine()){
String s = stdin.nextLine();
String [] words = s.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\\
s+"); //stores strings as words after converting to lowercase and getting rid of punctuation
for(int i = 0; i < words.length; i++){
int count = 0; //temporary so program can run
for(int j = 0; j < words.length; j++){
if( words[i] == words[j] )
count++;
System.out.println("word count: → " + words[i] + " " + count);
}
}
}
I would use something like this:
import java.util.ArrayList;
import java.util.Scanner;
public class WCount {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
String[] wordArray = new String[10000];
int[] wordCount = new int[10000];
int numWords = 0;
while (stdin.hasNextLine()) {
String s = stdin.nextLine();
ArrayList<String> noDuplicated = new ArrayList<String>();
String[] words = s.replaceAll("[^a-zA-Z ]", "").toLowerCase()
.split("\\s+"); // stores strings as words after converting
// to lowercase and getting rid of
// punctuation
//Array that contains the words without the duplicates ones
for (int i = 0; i < words.length; i++) {
if(!noDuplicated.contains(words[i]))
noDuplicated.add(words[i]);
}
//Count and print the words
for(int i=0; i<noDuplicated.size();i++){
int count = 0;
for (int j = 0; j < words.length; j++) {
if (noDuplicated.get(i).equals(words[j]))
count++;
}
System.out.println("word count: → " + words[i] + " "
+ count);
}
}
}
}
output:
This is a test, this is is
word count: → this 2
word count: → is 3
word count: → a 1
word count: → test 1
Hope it is usefull!
This works for me. Although iterating through the complete possible array is silly. It would work easier with ArrayList. But as I am not sure if you are allowed to use it.
import java.util.Scanner;
public class WCount {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
int[] wordCount = new int[1000];
String[] wordList = new String[1000];
int j = 0;
while (stdin.hasNextLine()) {
String s = stdin.nextLine();
String[] words = s.split("\\W+");
for (String word : words) {
int listIndex = -1;
for (int i = 0; i < wordList.length; i++) {
if (word.equals(wordList[i])) {
listIndex = i;
}
}
if (listIndex > -1) {
wordCount[listIndex]++;
} else {
wordList[j] = word;
wordCount[j]++;
j++;
}
}
for (int i = 0; i < j; i++) {
System.out.println("the word: " + wordList[i] + " occured " + wordCount[i] + " time(s).");
}
}
}
}
output:
this is a test. this is cool.
the word: this occured 2 time(s).
the word: is occured 2 time(s).
the word: a occured 1 time(s).
the word: test occured 1 time(s).
the word: cool occured 1 time(s).
You can use a hash table here. I am not going to write code for you, but here is simple pseudo algorithm:
if hashTable contains word
hashTable.put(word, words.value + 1)
else hashTable.put(word, 1)
Do this for each word in the word array. After all the words have been handled, you simply print each key (word) in the hash table with its value (number of times it appeared).
Hope this helps!
figured this out...simpler way..
import java.util.Vector;
public class Get{
public static void main(String[]args){
Vector<String> ch = new Vector<String>();
String len[] = {"this", "is", "this", "test", "is", "a", "is"};
int count;
for(int i=0; i<len.length; i++){
count=0;
for(int j=0; j<len.length; j++){
if(len[i]==len[j]){
count++;
}
}
if(count>0){
if(!ch.contains(len[i])){
System.out.println(len[i] + " - " + count);
ch.add(len[i]);
}
}
}
}
}
Output:
this - 2
is - 3
test - 1
a - 1
My implementation:
public static void main(final String[] args) {
try (Scanner stdin = new Scanner(System.in)) {
while (stdin.hasNextLine()) {
Map<String, AtomicInteger> termCounts = new HashMap<>();
String s = stdin.nextLine();
String[] words = s.toLowerCase().split("[^a-zA-Z]+");
for (String word : words) {
AtomicInteger termCount = termCounts.get(word);
if (termCount == null) {
termCount = new AtomicInteger();
termCounts.put(word, termCount);
}
termCount.incrementAndGet();
}
for (Entry<String, AtomicInteger> termCount : termCounts.entrySet()) {
System.out.println("word count: " + termCount.getKey() + " " + termCount.getValue());
}
}
}
}
Related
I'm recieving issue with the output can anyone help me with it?
It is a code for finding how many times a particular name has been repeated.
package example1;
import java.util.Scanner;
public class example1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i,j,t,c;
String a[]=new String[10];
String b[]=new String[10];
Scanner sc=new Scanner(System.in);
for(i=0;i<10;i++)
{
a[i]=sc.nextLine();
b[i]=a[i];
}
for(i=0;i<10;i++)
{
c=0;
for(j=i+1;j<9;j++)
{
if(b[j]==b[i])
{
c++;
for(t=j;t<10;t++)
{
b[t]=b[t+1];
}
}
}
System.out.print(b[i]+" is repeated "+ c +" times ");
}
}
}
Try this.
String[] arr = new String[] {"a","b","c","d","a","b","c","a","b","a"};
List<String> list = Arrays.asList(arr);
Set<String> set = new HashSet<>(list);
for(String name : set)
System.out.println(name + " is repeated " + Collections.frequency(list, name) + " times");
If you want your comparison to be case insensitive, then try this.
String[] arr = new String[] {"A","B","c","D","a","b","c","a","b","a"};
List<String> list = new ArrayList<>(10);
for(String name : arr)
list.add(name.toLowerCase());
Set<String> set = new HashSet<>(list);
for(String name : set)
System.out.println(name + " is repeated " + Collections.frequency(list, name) + " times");
Will require more space though.
The following code should help for determining the repetition
public class Repetation {
public static void main(String[] args) {
String string = "Sam sam is good boy james is sams friend clyra is clyra";
int count;
string = string.toLowerCase();
String words[] = string.split(" ");
System.out.println("Duplicate words: ");
for(int i = 0; i < words.length; i++) {
count = 1;
for(int j = i+1; j < words.length; j++) {
if(words[i].equals(words[j])) {
count++;
words[j] = "0";//making it 0 for future reference
}
}
if(count > 1 && words[i] != "0")
System.out.println(words[i]);
}
}
}
public static int countWord(String input, String text) {
int index = input.indexOf(text);
if (index == -1 || text.isEmpty()) {
return 0;
}
int count = 0;
do {
count++;
index = input.indexOf(text, index + text.length());
} while (index > 0 && index < input.length());
return count;
}
This code will return 4:
int total = countWord("abcs8abc88habcabci7h", "abc");
class Main{
public static void main (String str[]) throws IOException{
Scanner scan = new Scanner (System.in);
String message = scan.nextLine();
String[] sWords = {" qey ", " $ "," ^^ "};
int lenOfArray = sWords.length;
int c = 0;
int[] count = {0,0,0};
Getting the error, "java.lang.StringIndexOutOfBoundsException: String index out of range: -1" , in one of the for loops. I want the program to check for each substring in the sWord array and count how many times it occurs in the main message input.
for (int x = 0; x < sWords.length; x++){
for (int i = 0, j = i + sWords[x].length(); j < message.length(); i++){
if ((message.substring(i,j)).equals(sWords[x])){
count[c]++;
}
}
}
}
}
Following your approach, you need to set the value of jwithin the inner loop. Otherwise, it is only assigned on the first iteration. This changes the upper bound in the inner for loop as shown below. You also need to increment the counter index c after you search for an sWord.
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class MyClass {
public static void main (String str[]) throws IOException {
Scanner scan = new Scanner(System.in);
String message = scan.nextLine();
String[] sWords = {" qey ", " $ ", " ^^ "};
int lenOfArray = sWords.length;
int c = 0;
int[] count = {0, 0, 0};
for (int x = 0; x < sWords.length; x++) {
for (int i = 0; i <= message.length()-sWords[x].length(); i++) {
int j = i + sWords[x].length();
if ((message.substring(i, j).equals(sWords[x]))) {
count[c]++;
}
}
++c;
}
}
}
You can find number of occurrences of each string in sWords in the code below:
public static void main(String[] args) {
try {
Scanner scan = new Scanner(System.in);
String message = scan.nextLine();
String[] sWords = {" qey ", " $ ", " ^^ "};
int lenOfArray = sWords.length;
int c = 0;
int[] count = {0, 0, 0};
for (int i = 0; i < lenOfArray; i++) {
while (c != -1) {
c = message.indexOf(sWords[i], c);
if (c != -1) {
count[i]++;
c += sWords[i].length();
}
}
c = 0;
}
int i = 0;
while (i < lenOfArray) {
System.out.println("count[" + i + "]=" + count[i]);
i++;
}
} catch (Exception e) {
e.getStackTrace();
}
}
It's better to use apache commons lang StringUtils
int count = StringUtils.countMatches("a.b.c.d", ".");
In a given string, I want to find the longest word then print it in the console.
The output I get is the second longest word i.e "Today", but I should get "Happiest" instead.
May I know what I am doing wrong? Is there a better/different way to find the longest word in a string?
public class DemoString {
public static void main(String[] args) {
String s = "Today is the happiest day of my life";
String[] word = s.split(" ");
String longword = " ";
for (int i = 0; i < word.length; i++)
for (int j = 1 + i; j < word.length; j++)
if (word[i].length() >= word[j].length())
longword = word[i];
System.out.println(longword + " is the longest word with " + longword.length() + " characters.");
System.out.println(rts.length());
}
}
Here is a "one-liner" you can use with the Java 8 streams API:
import java.util.Arrays;
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
String s = "Today is the happiest day of my life";
String longest = Arrays.stream(s.split(" "))
.max(Comparator.comparingInt(String::length))
.orElse(null);
System.out.println(longest);
}
}
Output:
happiest
Try it out here.
// the below Java Program will find Smallest and Largest Word in a String
class SmallestAndLargestWord
{
static String minWord = "", maxWord = "";
static void minMaxLengthWords(String input)
{
// minWord and maxWord are received by reference
// and not by value
// will be used to store and return output
int len = input.length();
int si = 0, ei = 0;
int min_length = len, min_start_index = 0,
max_length = 0, max_start_index = 0;
// Loop while input string is not empty
while (ei <= len)
{
if (ei < len && input.charAt(ei) != ' ')
{
ei++;
}
else
{
// end of a word
// find curr word length
int curr_length = ei - si;
if (curr_length < min_length)
{
min_length = curr_length;
min_start_index = si;
}
if (curr_length > max_length)
{
max_length = curr_length;
max_start_index = si;
}
ei++;
si = ei;
}
}
// store minimum and maximum length words
minWord = input.substring(min_start_index, min_start_index + min_length);
maxWord = input.substring(max_start_index, max_length);
}
// Driver code
public static void main(String[] args)
{
String a = "GeeksforGeeks A Computer Science portal for Geeks";
minMaxLengthWords(a);
// to take input in string use getline(cin, a);
System.out.print("Minimum length word: "
+ minWord
+ "\nMaximum length word: "
+ maxWord);
}
}
**
Input : "GeeksforGeeks A computer Science portal for Geeks"
Output : Minimum length word: A
Maximum length word: GeeksforGeeks
**
instead it should be:
for(int i=0; i < word.length; i++)
{
if(word[i].length() >= rts.length())
{
rts = word[i];
}
}
String s= "Today is the happiest day of my life by vijayakumar";
String [] word = s.split(" ");
String maxlethWord = "";
for(int i = 0; i < word.length; i++){
if(word[i].length() >= maxlethWord.length()){
maxlethWord = word[i];
}
}
System.out.println(maxlethWord);
I haven't seen an answer where you create a list of the words.
So here is another way to solve the problem:
String s = "Today is the happiest day of my life";;
List<String> strings = Arrays.asList(s.split(" "));
String biggestWord = Collections.max(strings, Comparator.comparing(String::length));
System.out.println(biggestWord);
Output:
happiest
You can try like ,
String s="Today is the happiest day of my life";
String[] word=s.split(" ");
String rts=" ";
for(int i=0;i<word.length;i++){
if(word[i].length()>=rts.length()){
rts=word[i];
}
}
System.out.println(rts);
System.out.println(rts.length());
Try this one.
public static void main( String[] args )
{
String s = "Today is the happiest day of my life";
String[] word = s.split( " " );
String rts = " ";
for ( int i = 0; i < word.length; i++ )
{
if ( word[i].length() > rts.length() )
rts = word[i];
}
System.out.println( rts );
}
for(int i=0;i<word.length;i++){
for(int j=0;j<word.length;j++){
if(word[i].length()>=word[j].length()){
if(word[j].length()>=rts.length()) {
rts=word[j];
}
} else if(word[i].length()>=rts.length()){
rts=word[i];
}
}
}
import java.io.*;
import java.util.*;
public class chopMiddle {
public static void main(String[] args) {
String sample = "1,2,3,4,5";
StringTokenizer tokenizer = new StringTokenizer(sample, ",");
while(tokenizer.hasMoreTokens()) {
int convertedToInt = Integer.parseInt(tokenizer.nextToken());
int [] array = new int [3];
for(int i = 0; i < array.length; i++)
{
array[i] = Integer.parseInt(tokenizer.nextToken());
System.out.println(array[i] + " ");
}
}
}
}
I try to break the string into tokens and uses Integer.parseInt method to convert the tokens into int value.
I want to return an array of size 3 which contains the int values of the 2nd to the 4th integers from the string to the caller. Am i doing something wrong, because it shows below message when i compiled
Exception in thread "main" java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(StringTokenizer.java:349)
at chopMiddle.main(chopMiddle.java:18)
The problem will be when it gets to the 5th token, it will read it, then create a new array and try to read 3 more.
After you have read the 2nd, 3rd and 4th, you should break both loops.
while(tokenizer.hasMoreTokens()) {
int convertedToInt = Integer.parseInt(tokenizer.nextToken());
int [] array = new int [3];
for(int i = 0; i < array.length && tokenizer.hasMoreTokens(); i++) //check hasMoreTokens
{
array[i] = Integer.parseInt(tokenizer.nextToken());
System.out.println(array[i] + " ");
}
}
you need to check every time when you call: tokenizer.nextToken()
If you check if tokenizer has more elements in the for loop itself then you won't require while loop at all.
try below example :
public static void main(String[] args) {
String sample = "1,2,3,4,5";
StringTokenizer tokenizer = new StringTokenizer(sample, ",");
int[] array = new int[3];
for (int i = 0; i < array.length && tokenizer.hasMoreTokens(); i++) {
array[i] = Integer.parseInt(tokenizer.nextToken());
System.out.println(array[i] + " ");
}
}
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);
}
}