package removeduplicates;
public class countchar {
public static void main(String[] args) {
countcharacter("mmaasshaa");
}
public static void countcharacter(String word1)
{
char ch[]= word1.toCharArray();
int count=0;
for(int i=0; i<ch.length; i++)
{
for(int j=0; j<ch.length; j++)
{
if(ch[i]==ch[j])
{
count++;
}
}
System.out.println(ch[i] + count);
}
}
}
output should be -
m2
a4
s2
h1
Instructor
Yogesh Chawla Replied on 26/12/2019
Hi Manisha,
You can write something like this. This will give you the first non-repetitive character inside the arrray. In your case, it is 'h'
public class Countchar {
public static void main(String[] args) {
countcharacter("mmaasshaa");
}
public static void countcharacter(String word1) {
//char ch[] = word1.toCharArray();
//System.out.println("The number of characters in array are " + ch.length);
// Assuming total number of characters inside Array
int NO_OF_CHARS = 256;
// Initialize all characters as absent.
int arr[] = new int[NO_OF_CHARS];
for (int i = 0;i < NO_OF_CHARS; i++)
arr[i] = -1;
// After below loop, the value of arr[x] is going to be index x if x appears only once
// else the value is going to be either -1 or -2.
// This is a way to find out elements inside Arrays using charAt() function
for (int i = 0; i < word1.length(); i++) {
if (arr[word1.charAt(i)] == -1)
arr[word1.charAt(i)] = i;
else
arr[word1.charAt(i)] = -2;
}
int res = Integer.MAX_VALUE;
for (int i = 0; i < NO_OF_CHARS; i++)
// If the character occurs only once and appears before the current result, then update the result
if (arr[i] >= 0)
res = Math.min(res, arr[i]);
System.out.println("The position of non-repetive character inside array is " + res);
int index = res;
if (index == Integer.MAX_VALUE)
System.out.print("Either all characters are " +
"repeating or string is empty");
else
System.out.print("First non-repeating character"+
" is " + word1.charAt(index));
/*for (int j = 0; j < word1.length(); j++) {
if (ch[i] == ch[j]) {
count++;
}
}
System.out.println(ch[i] + count);*/
}
}
If you want something more from the code, Just let me know.