How to find number of distinct characters in a string - java

I have to count the number of distinct characters alphabet in the string, so in this case the count will be - 3 (d, k and s).
Given the following String:
String input;
input = "223d323dk2388s";
count(input);
My Code :
public int count(String string) {
int count=0;
String character = string;
ArrayList<Character> distinct= new ArrayList<>();
for(int i=0;i<character.length();i++){
char temp = character.charAt(i);
int j=0;
for( j=0;j<distinct.size();j++){
if(temp!=distinct.get(j)){
break;
}
}
if(!(j==distinct.size())){
distinct.add(temp);
}
}
return distinct.size();
}
Output : 3
Are there any native libraries which return me the number of characters present in that string ?

With java 8 it is much easy. You could use something like this
return string.chars().distinct().count();

One way is to maintain an array and then fill it up and get the total. This checks for all characters including special characters and numbers.
boolean []chars = new boolean[256];
String s = "223d323dk2388s";
for (int i = 0; i < s.length(); ++i) {
chars[s.charAt(i)] = true;
}
int count = 0;
for (int i = 0; i < chars.length; ++i) {
if (chars[i]) count++;
}
System.out.println(count);
Here's an alternative if you want to calculate the count only of letters, not including numbers and special symbols. Note that capital and small alphabets are different.
boolean []chars = new boolean[56];
String s = "223d323dk2388szZ";
for (int i = 0; i < s.length(); ++i) {
char ch = s.charAt(i);
if (ch >=65 && ch <= 90) {
chars[ch - 'A'] = true;
} else if (ch >= 97 && ch <= 122) {
chars[ch - 'a' + 26] = true; //If you don't want to differentiate capital and small differently, don't add 26
}
}
int count = 0;
for (int i = 0; i < chars.length; ++i) {
if (chars[i]) count++;
}
System.out.println(count);
Another way of doing it is using a Set.
String s = "223d323dk2388s";
Set<Character> set = new HashSet<Character>();
for (int i = 0; i < s.length(); ++i) {
set.add(s.charAt(i));
}
System.out.println(set.size());
If you don't want numbers and special symbols.
String s = "223d323dk2388s";
Set<Character> set = new HashSet<Character>();
for (int i = 0; i < s.length(); ++i){
char ch = s.charAt(i);
if ((ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122))
set.add(s.charAt(i));
}
System.out.println(set.size());

String s="InputString";
String p="";
char ch[]=s.toCharArray();
for(int i=0;i<s.length();i++)
{
for(int j=i+1;j<s.length();j++)
{
if(ch[i]==ch[j])
{
ch[j]=' ';
}
}
p=p+ch[i];
p = p.replaceAll("\\s","");
}
System.out.println(p.length());

To those coming here looking for a solution in Kotlin:
val countOfDistinctCharacters = string.toCharArray().distinct().size

Related

How to compute the frequency of occurrence of '+' and '++' in Java?

I want to calculate the frequency of the occurrence of all the operators from an input text file. The file contains the operators + and ++. How can I distinguish their respective frequency, as my program treats ++ as 2 distinct + operators rather than 1 ++?
Here is my code (input7.txt is a test file):
public static void main(String[] args) throws IOException {
String string = new String(Files.readAllBytes(Paths.get("input7.txt"))); //String to be counted
int frequencyArray[] = new int[string.length()];
int frequencyArray2[] = new int[string.length()];
char stringArray[] = string.toCharArray(); //Array of characters
int i, j;
//Count characters
for (i = 0; i < string.length(); i++) {
frequencyArray[i] = 1;
//frequencyArray2[i] = 1;
for(j = i + 1; j < string.length(); j++)
{
if(stringArray[i] == stringArray[j])
{
frequencyArray[i]++;
stringArray[j] = '0'; //To avoid revisiting a character
}
}
}
//Display results
System.out.println("Characters and their corresponding frequencies");
for (i = 0; i < frequencyArray.length; i++) {
if (stringArray[i] != ' ' && stringArray[i] != '0') {
System.out.println(stringArray[i] +"-" + frequencyArray[i]);
}
}
}
This works for me:
String s = "sdfasd++ sdfadsf+asdf sdf++sadfasdf++sadfsdf+asdfasdf++";
// create Set with all distinct characters
Set<Character> chars = new HashSet<Character>();
for (int i = 0; i < s.length(); i++) {
chars.add(s.charAt(i));
}
// count distinct characters and put Results in HashMap
Map<Character, Integer> counts = new HashMap<Character, Integer>();
for (Character c : chars) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == c)
count++;
}
counts.put(c, count);
}
// Count double-Character-Operators like this
int countPlusPlus = 0;
for (int i = 0; i < s.length() - 1; i++) {
if (s.substring(i, i + 2).equals("++"))
countPlusPlus++;
}
// Calculate totals like this
int singleplusTotal = counts.get('+');
System.out.println("Single Plus total" + singleplusTotal);
System.out.println("Double Plus total" + countPlusPlus);
System.out.println("Only single Plus" + (singleplusTotal - countPlusPlus * 2));

adding characters in an array at specific points

I'm working on a Caesar cipher and I've gotten the majority of the code to work as planned.
the code is supposed to
remove all special characters and spaces
bring everything to uppercase
add spaces at an inputted interval any additional leftover spaces with x's
so for example if i were to type
plaintext: Hi im Doug
key: 1
buffer: 3
my output should be
IJJ NEP VHX
now I've gotten everything to work but the buffer part
this is my code in its entirety
import java.util.Scanner;
import java.lang.String;
public class Main {
public static void main(String[] args) {
System.out.print("Enter plaintext: ");
Scanner pTextInp = new Scanner(System.in);
String pText = pTextInp.nextLine();
System.out.print("Enter key value: ");
Scanner kInp = new Scanner(System.in);
int key = kInp.nextInt();
pText = normalizeText(pText);
pText = caesarify(pText, key);
System.out.print("Enter desired grouping number: ");
Scanner grpInp = new Scanner(System.in);
int grpInt = grpInp.nextInt();
pText = groupify(grpInt, pText);
System.out.println(pText);
}
// CONVERT STRING TO A CHAR ARRAY
public static char[] sArray(String s) {
int sLen = s.length();
char[] sChar = new char[sLen + 1];
for (int i = 0; i < sLen; i++){
sChar[i] = s.charAt(i);
}
return sChar;
}
public static String caesarify(String s, int k) {
int sLen = s.length();
char cText[] = sArray(s);
for (int i = 0; i < sLen; i++){
int j = cText[i] - 65;
int l = (((j + k) % 26) + 65);
cText[i] = (char) l;
}
s = new String(cText);
return s;
}
// normalizes text (removes all spaces and special characters)
public static String normalizeText(String s) {
int sLen = s.length();
char[] t1 = s.toCharArray();
for (int i = 0; i < sLen; i++ ){
if(t1[i] < 'A' || t1[i] > 'z' || (t1[i] > 'Z' && t1[i] < 'a')) {
t1[i] = ' ';
}
else{
t1[i] = s.charAt(i);
}
}
String t = new String(t1);
t = t.replaceAll(" ", "" );
t = t.toUpperCase();
return t;
}
public static String groupify(int i , String s){
int sLen = s.length();
char[] t = new char[sLen];
for (int j = 0; j < s.length(); j++){
t[j] = s.charAt(j);
if ( j % i == 0) {
t[j] = ' ';
sLen++;
}
}
s = new String(t);
return s;
}
and this is the section in particular that i think is the issue
public static String groupify(int i , String s){
int sLen = s.length();
char[] t = new char[sLen];
for (int j = 0; j < s.length(); j++){
t[j] = s.charAt(j);
if ( j % i == 0) {
t[j] = ' ';
sLen++;
}
}
s = new String(t);
return s;
}
with this this if i input
Hi Im Doug
I get
JJ EP H
as output
Thanks a bunch
Currently your code t[i] += ' ' is adding the space character's value to value in the array. That's not what you want. Rather you want to be storing a space in next position. I also suggest that you use better names for your variable - single character variables should generally only be used for indexes.
int pos = 0;
for (int j = 0; j < input.length(); j++)
result[pos++] = input.charAt(j);
if ( j % group == 0) {
result[pos++] = ' ';
}
}
For the code You have highlighted you are missing curly brackets after the for Loop. Try to define j outside the for-loop and assign the value 0 to j in the for-loop. It would be a better practice if you Store the size of your new Char-Array in a separate variable as it is easier to read when finding bugs in the code.

java, how to find the amount of letter in a string without repeats

I'm trying to build a function, that gets a string of letters, and prints the amount of each letter in the string.
for example:
input: String = "aaabbaccxyxyx"
output: 4a2b2c3x2y
This is what I've come up with:
public class Q1 {
public static String numLetters(String s){
String end = new String();
int counter = 0;
char c,d;
for(int i=0; i<s.length();i++){
c = s.charAt(i);
for(int j=0; j<s.length();j++){
d = s.charAt(j);
if(c == d){
counter++;
}
}
end = end + counter+c;
counter = 0;
}
return end;
}
but, this is the output: 4a4a4a2b2b4a2c2c3x2y3x2y3x
A lot of repeats..
Any help how to make it right?
Keep in mind, the function needs to return a string, not just prints it out.
Thanks! =)
I would make an int array to keep the count of each letter in in the string. Because there are 26 letters, the length of the array should be 26:
public static String numLetters(String s) {
int[] count = new int[26];
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
count[(int)(c - 'a')]++;
}
String ans = "";
for (int i = 0; i < 26; i++) {
if (count[i] != 0) {
ans += String.valueOf(count[i]) + (char)(i + 'a');
}
}
return ans;
}
A straightforward variant could look like this:
public static String countChars(String arg) {
String res = "";
boolean[] counted = new boolean[arg.length()];
for (int i = 0; i < counted.length; i++) {
if (!counted[i]) {
char c = arg.charAt(i);
int counter = 1;
for (int j = i + 1; j < counted.length; j++) {
if (arg.charAt(j) == c) {
counter++;
counted[j] = true;
}
}
res += counter + "" + c;
}
}
return res;
}
If you want to keep your original structure, I suggest using a StringBuilder so that you can delete characters that you have already seen. In case you delete a character, you have to adjust your indexes i and j.
public static String numLetters(String str){
StringBuilder s = new StringBuilder(s);
String end = new String();
int counter = 0;
char c,d;
for(int i=0; i<s.length();i++){
c = s.charAt(i);
for(int j=0; j<s.length();j++){
d = s.charAt(j);
if(c == d){
s.deleteCharAt(j);
if (i >= j) i--;
j--;
counter++;
}
}
end = end + counter+c;
counter = 0;
}
return end;
}
Try this:
int count = StringUtils.countMatches("a.b.c.d", ".");

How to print an object array correctly? [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 8 years ago.
main class
public CustomString[] split(char delimiter) {
// char n;
char[] split = null;
int numOfSplit = 1;
int objectLocation=0;
for (int h = 0; h < this.data.length; h++) {
if (delimiter == this.data[h]) {
numOfSplit++;
}
}
CustomString[] splitter = new CustomString[numOfSplit];
for (int i = 0; i < this.data.length; i++) {
if (delimiter == this.data[i]) {
// n = 32;//unicode for space}
split = new char[i];
for (int j = 0; j < split.length; j++) {
char z = this.data[j];
split[j] = z;
objectLocation++;
}
}
splitter[objectLocation] = new CustomString(split);
}
return splitter;
}
tester class:
System.out.print("Delimiter: ");
String delimiter = input.next();
char[] deli = delimiter.toCharArray();
char delim = deli[0];
System.out.println("Splitted String: " + blah.split(delim));
result: [LCustomString;#55f96302
main class completed
import java.util.Scanner;
import java.util.Arrays;
public class CustomString {
private char[] data;
public CustomString() {
} // no arg constructor
public CustomString(char[] data) {
this.data = data;
} // constructor
public CustomString changeCase() { // type: CustomString
char n;
char[] newArray = new char[this.data.length];// this.data;
// char charNewA
for (int i = 0; i < newArray.length; i++) {
n = this.data[i];
// char[] number = new char[1];
if (n >= 65 && n <= 90) {
n += 32;
}// if capital char change to lower char
else if (n >= 97 && n <= 122) {
n -= 32;
}// if lower char change to capital char
// create a new array with n properties
newArray[i] = n;
}
return new CustomString(newArray);
} // returns a new CustomString where the case of each letter is changed to
// the opposite
public char charAt(int index) {
char charIndex = this.data[index - 1];
return charIndex;
} // returns character as a given index
public int compareTo(CustomString rhs) { // take off comments
int value = 0;
int loopSize;
if (this.data.length < rhs.data.length) {
loopSize = this.data.length;
} else {
loopSize = rhs.data.length;
}
for (int i = 0; i < loopSize; i++) {
char char1 = this.data[i];
char char2 = rhs.data[i]; // should be equal to 2nd customString
if (char1 != char2) {
value = char1 - char2;
// if (char1 > char2) {
// value = char1-char2; //pos??
// } else if (char1 < char2) {
// value =
// }
}
}
return value;
} // compares 2 strings lexographically. return 0 if two same. return + is
public int compareToIgnoreCase(CustomString rhs) {
char[] newArrayCompareToIgnoreCase = new char[this.data.length];
// newArrayCompareToIgnoreCase = this.data;
char[] newArrayCompareToIgnoreCase2 = new char[rhs.data.length];
// newArrayCompareToIgnoreCase2 = rhs.data;
char n, m;
int value = 0;
int loopSize;
if (this.data.length < rhs.data.length) {
loopSize = this.data.length;
} else {
loopSize = rhs.data.length;
}
for (int i = 0; i < loopSize; i++) {
n = this.data[i];
// char[] number = new char[1];
if (n >= 97 && n <= 122) {
n -= 32;
}// if lower char change to capital char
newArrayCompareToIgnoreCase[i] = n;
m = rhs.data[i];
if (m >= 97 && m <= 122) {
m -= 32;
}// if lower char change to capital char
newArrayCompareToIgnoreCase2[i] = m;
// by now everything should be lowercase
for (int j = 0; j < loopSize; j++) {
char char1 = newArrayCompareToIgnoreCase[j];
char char2 = newArrayCompareToIgnoreCase2[j];
if (char1 == char2) {
value = 0;
}
if (char1 != char2) {
value = char1 - char2;
}
}
}
return value;
} // compares two string but casing douse not matter
public CustomString concat(CustomString rhs) {
char n, m;
char[] newArrayConcat = new char[this.data.length + rhs.data.length + 2];
for (int i = 0; i < this.data.length; i++) {
n = this.data[i];
// m = rhs.data[i];
newArrayConcat[i] = n;
// newArrayConcat[i+this.data.length]= m;
}
for (int j = 0; j < rhs.data.length; j++) {
m = rhs.data[j];
newArrayConcat[j + this.data.length] = m; // +1
}
return new CustomString(newArrayConcat); // change?
}// returns a new CustomString object by concatenating source string and
// parameter string
// CustomString
public boolean equals(CustomString rhs) {
char[] newArrayEquals = new char[this.data.length];
char[] newArrayEquals2 = new char[rhs.data.length];
boolean equals = false;
int length;
char n, m;
if (this.data.length > rhs.data.length) {
length = rhs.data.length;
} else {
length = this.data.length;
}
for (int i = 0; i < length; i++) {
n = this.data[i];
m = rhs.data[i];
newArrayEquals[i] = n;
newArrayEquals2[i] = m;
}
for (int j = 0; j < length; j++) {
char char1 = newArrayEquals[j];
char char2 = newArrayEquals2[j];
if (char1 != char2) {
equals = false;
break;
} else if (char1 == char2) {
equals = true;
}
}
return equals;
} // Returns true or false based on whether or not the two strings are
// equal. NOTE: Does not ignore case
public boolean equalsIgnoreCase(CustomString rhs) {
int length;
if (this.data.length > rhs.data.length) {
length = rhs.data.length;
} else {
length = this.data.length;
}
char[] newArrayEqualsToIgnoreCase = new char[this.data.length];
char[] newArrayEqualsToIgnoreCase2 = new char[rhs.data.length];
char n, m;
boolean equalsIgnoreCase = false;
for (int i = 0; i < length; i++) { // must compare which string is
// longer or else if
// //newArrayEqualsToIgnoreCase.length
n = this.data[i];
m = rhs.data[i];
if (n >= 65 && n <= 90) {
n += 32;
}
if (m >= 65 && m <= 90) {
m += 32;
}// changes everything to lower case
newArrayEqualsToIgnoreCase[i] = n;
newArrayEqualsToIgnoreCase2[i] = m;
}
for (int j = 0; j < length; j++) { // this.data.length
char char1 = newArrayEqualsToIgnoreCase[j];
char char2 = newArrayEqualsToIgnoreCase2[j];
if (char1 != char2) {
equalsIgnoreCase = false;
break;
} else if (char1 == char2) {
equalsIgnoreCase = true;
}
}
return equalsIgnoreCase; // change?
} // Same as equals but ignores the case
public int length() {
int charLength = this.data.length;
return charLength; // change?
} // Returns the length of the CustomString object
public CustomString[] split(char delimiter) {
// char n;
char[] split = null;
int numOfSplit = 1;
int objectLocation=0;
for (int h = 0; h < this.data.length; h++) {
if (delimiter == this.data[h]) {
numOfSplit++;
}
}
CustomString[] splitter = new CustomString[numOfSplit];
for (int i = 0; i < this.data.length; i++) {
if (delimiter == this.data[i]) {
// n = 32;//unicode for space}
split = new char[i];
for (int j = 0; j < split.length; j++) {
char z = this.data[j];
split[j] = z;
objectLocation++;
}
}
splitter[objectLocation] = new CustomString(split);
}
return splitter;
} // Returns a CustomString array, where each element of the array is a
// CustomString object created by splitting the source string based
// on the given char delimiter. This is an easier version of the split
// method provided in the String class and
// you only need to split on one character. The output array should NOT
// contain the delimiter character.
public boolean startsWith(CustomString prefix) {
boolean startsWithEqual = false;
char[] startsWith1 = new char[prefix.data.length];
char[] startsWith2 = new char[prefix.data.length];
char m, n;
for (int i = 0; i < prefix.data.length; i++) {
m = this.data[i];
n = prefix.data[i];
startsWith1[i] = m;
startsWith2[i] = n;
}
for (int j = 0; j < prefix.data.length; j++) {
if (startsWith1[j] == startsWith2[j]) {
startsWithEqual = true;
}
if (startsWith1[j] != startsWith2[j]) {
startsWithEqual = false;
break;
}
}
return startsWithEqual;
} // Returns true if the source CustomString starts with the given prefix
public boolean endsWith(CustomString suffix) {
boolean endsWithEqual = false;
char[] endsWith1 = new char[suffix.data.length];
char[] endsWith2 = new char[suffix.data.length];
char m, n;
for (int i = 0; i < suffix.data.length; i++) {
n = suffix.data[i];
endsWith2[i] = n;
}
int k = 0;
for (int i = this.data.length - suffix.data.length; i < this.data.length; i++) {
m = this.data[i];
endsWith1[k] = m;
k++;
}
for (int j = 0; j < suffix.data.length; j++) {
if (endsWith1[j] == endsWith2[j]) {
endsWithEqual = true;
}
if (endsWith1[j] != endsWith2[j]) {
endsWithEqual = false;
break;
}
}
return endsWithEqual;
}
// Returns true if the source CustomString contains the parameter
public CustomString substring(int srcBegin) {
char[] newArraySub1;
if (srcBegin == 0) {
newArraySub1 = new char[this.data.length - srcBegin];
} else {
newArraySub1 = new char[this.data.length - srcBegin + 1];
}
char n;
for (int i = srcBegin; i < newArraySub1.length; i++) {
n = this.data[i];// -1
newArraySub1[i] = n;
}
return new CustomString(newArraySub1);
} // Returns a new CustomString object created by finding the substring of
// the source string starting
// with src Begin and going to the end of the source string
public CustomString substring(int srcBegin, int srcEnd) {
char n;
char[] newArraySub2 = new char[this.data.length - srcBegin];
for (int i = srcBegin; i < srcEnd; i++) {
n = this.data[i];
newArraySub2[i] = n;
}
return new CustomString(newArraySub2);
}// Returns a new CustomString object created by finding the substring of
// the source starting with srcBegin and ending at srcEnd –
public CustomString titleize() {
char n, m;
char[] titleizedChar = new char[this.data.length];
for (int j = 0; j < this.data.length; j++) {
m = this.data[j];
if (m >= 65 && m <= 90) {
m += 32;
titleizedChar[j] = m;
}
for (int i = 0; i < 1; i++) {
n = this.data[i];
if (n >= 97 && n <= 122) {
n -= 32;
}
titleizedChar[i] = n;
}
titleizedChar[j] = m;
}
return new CustomString(titleizedChar); // change?
} // Returns a new CustomString object where the first character or every
// word is capitalized.
public CustomString toLowerCase() {
char[] toLowCase = new char[this.data.length];
for (int i = 0; i < toLowCase.length; i++) {
char n = this.data[i];
if (n >= 65 && n <= 90) {
n += 32;
}
toLowCase[i] = n;
}
return new CustomString(toLowCase);
} // Returns a new CustomString object with all lower case letters.
public CustomString toUpperCase() { // should be similar to lower case do
char[] toUpperCase = new char[this.data.length];
for (int i = 0; i < toUpperCase.length; i++) {
char n = this.data[i];
if (n >= 97 && n <= 122) {
n -= 32;
}
toUpperCase[i] = n;
}
return new CustomString(toUpperCase);
} // Returns a new CustomString object with all upper case letters.
public String toString() {
String toString1 = "";
for (int i = 0; i < this.data.length; i++) {
char n = this.data[i];
toString1 += n;
}
return toString1;
} // Returns a String representation of the CustomString object. This is the
// only place where you are allowed to use a String variable to build
// the output string and return it.
}// end of code
I'm trying to print each object inside the array but dont know how? Note: i already have a toString method.
Edit: I changed the main class from the original post at 10:45 pm i posted the wrong one
You could use
java.util.Arrays.toString(blah.split(delim));
For this to work, your CustomString class would need to provide a toString() method, too.
As per your question the blah.split(delim) is supposed to return an array of CustomString data type .
I am asuming that you have a class called CustomString ..
so in order to convert From CustomString type to normal string type you need to be specific about the CustomString .
Please mention the contents of the Class CustomString so that we could help you out
ok by the look of CustomString class it is storing an array of datatype char so but the problem is that the return type of split(delim) is an array of datatype CustomString so you will face problems while unboxing with tostring() .. give me a minute
You can use
System.out.println(new String(charArray))
or
Arrays.toString(charArray)
to convert character array into string for printing purpose.
you can also refers to
What does the output of a printed character array mean?
Instead of reading char 1 by 1 and append in the string. Simple use new String(data)
Unboxing Might help
try
System.out.println("Splitted String: " + blah.split(delim).toString());

How to count unique characters (only letters and numbers)

// I have a program where I am supposed to count unique characters, only letters and numbers and don't count repeating numbers or letters. However, I have a problem finding out a way for the program not to count spaces and symbols such as "!" "#" "#" "$". So If i type in Hello! I only want the program to say "4", but it says "5" because it counts the exclamation point. Here is my code so far:
public static int countUniqueCharacters(String text1) {
int count = 0;
for (int i = 0; i < text1.length(); i++) {
if (text1.substring(0, i).contains(text1.charAt(i) + ""))
System.out.println();
else
count++;
}
return count;
}
In your else block add a condition that the count will be incremented only if the given character is a letter or a digit.
if (Character.isLetter(text1.charAt(i)) || Character.isDigit(text1.charAt(i))) {
count++;
}
In your example:
public static int countUniqueCharacters(String text1) {
int count = 0;
for (int i = 0; i < text1.length(); i++) {
if (text1.substring(0, i).contains(text1.charAt(i) + "")) {
System.out.println();
} else if (Character.isLetter(text1.charAt(i)) || Character.isDigit(text1.charAt(i))) {
count++;
}
}
return count;
}
here's a sample code written in C# try and understand it. It compares with ascii and adds in a list
string input = Console.ReadLine();//input
List<char> CountedCharacters = new List<char>();
for (int i = 0; i < input.Length; i++)
{ //checking for numerics //checking for alphabets uppercase //checking for alphabets lowercase
if ((input[i] >= 45 && input[i] <= 57) || (input[i] >= 65 && input[i] <= 90) || (input[i] >= 97 && input[i] <= 122))
{
bool AlreadyExists = false;
for (int j = 0; j < CountedCharacters.Count; j++)
{
////checking if already exists
if (CountedCharacters[j]==input[i])
{
AlreadyExists = true;
break;
}
}
////adding in list if doesnt exists
if (!AlreadyExists)
{
CountedCharacters.Add(input[i]);
}
}
}
for (int i = 0; i < CountedCharacters.Count; i++)
{
Console.WriteLine(CountedCharacters[i]);
}
Try this one using regex. You can add and remove the characters you need from the expression to count what you need.
public static int countUniqueCharacters(String text1) {
String newText = text1.replaceAll("[^A-Za-z0-9()\\[\\]]", "");
Set<Character> tempSet = new HashSet<>();
for (char item : newText.toCharArray()) {
tempSet.add(item);
}
return tempSet.size();
}

Categories

Resources