// 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();
}
Related
I was wondering how to iterate over a string and to check how many hi's come out
For example, if the string is "hihi" the count should output 2.
This is what I have so far
public static int countHi(String str) {
int counter = 0;
for (int i = 0; i < str.length(); i++) {
if (str.substring(i, i + 1) == "h") {
if (str.substring(i, i + 1) == "i") {
counter = counter + 1;
}
}
}
return counter;
}
public static void main(String[] args) {
String str = "hihi";
int i = countHi(str);
System.out.println("number of hi = " + i);
}
You compare instances (like String) with .equals (not ==). However, here you can use == with String.charAt(int). Also, I would start with the second character and compare the character at the current index with i and the previous index with h. Like,
public static int countHi(String str) {
int counter = 0;
for (int i = 1; i < str.length(); i++) {
if (str.charAt(i - 1) == 'h' && str.charAt(i) == 'i') {
counter++;
}
}
return counter;
}
Alternatively, compare the character at the current index with h and the character at the next index with i (but now you need to stop iterating a character earlier). Like,
public static int countHi(String str) {
int counter = 0;
for (int i = 0; i < str.length() - 1; i++) {
if (str.charAt(i) == 'h' && str.charAt(i + 1) == 'i') {
counter++;
}
}
return counter;
}
Here's the easy way:
public static int countHi(String str) {
return split(str, -1).length - 1;
}
Note that you must pass -1 as the second parameter of split(); without it, trailing blanks would be pruned from the result.
For compactness and readability, maybe:
int count = 0;
Matcher matcher = Pattern.compile(“hi”).matcher(string)
while (matcher.find()) {
count++;
}
This approach will work for any Regular Expression pattern, although it won’t be the most efficient.
So, for class I have to code a program that determines how many positive integers are
1) Under 1,000,000
2) Have at least one 7 and a 9 in the number
3) Has to be done with the brute-force method.
While the answer is supposed to be 199,262, I keep getting 228530 due to duplicates, can someone take a look to see where I went wrong here? Thanks!
Similar problem but not the same: Java - numbers with at least one 7 and one 9 in its digit
boolean sevNine = false; // a combination of seven and nine in a number
boolean oneNine;
boolean oneSeven;
int counter = 0;
for (int i = 0; i<1000000; i++) //Runs numbers 1-1000000
{
oneSeven = false;
oneNine = false;
String number2 = " " + (i); //sets a nmber to a string
int length = number2.length() -1; //length goes up to the last character 0-j
for (int j= 0; j <= length; j++) //looking for the first 7 or 9 in string
{
char a = number2.charAt(j); //sets char to the next "letter"
if (a == '7' && oneSeven != true) //if the number is a 7 and there isnt already a seven
{
oneSeven = true; //now there is a seven,
for (int k = j+1; k <= length; k++) //checks from the next char up to the length for a 9
{
char b = number2.charAt(k);
if (b == '9')
{
sevNine = true;
}
}
}
else if (a == '9' && oneNine != true)
{
oneNine = true;
for (int l = j+1; l <= length; l++)
{
char b = number2.charAt(l);
if (b == '7')
{
sevNine = true;
}
}
}
if (sevNine == true)
{
counter++;
sevNine = false;
System.out.println(number2);
}
}
}
System.out.println(counter);
In Java 8 you can try:
public static void main(String[] args) {
final long count = IntStream.rangeClosed(0, 10_00_000)
.filter(i -> String.valueOf(i).contains("7") && String.valueOf(i).contains("9"))
.count();
System.out.println(count);
}
You are not breaking out of the loop once the sevNine is set to true and you increment the counter, so it keeps iterating over each digit on the same number even if it has already included the number... Just add a break statement to exit the for loop iterating over each digit once you increment the counter...
Here's the code.
public static void main(String[] args) {
boolean sevNine = false; // a combination of seven and nine in a number
boolean oneNine;
boolean oneSeven;
int counter = 0;
for (int i = 0; i < 1000000; i++) // Runs numbers 1-1000000
{
oneSeven = false;
oneNine = false;
String number2 = " " + (i); // sets a nmber to a string
int length = number2.length() - 1; // length goes up to the last character 0-j
for (int j = 0; j <= length; j++) // looking for the first 7 or 9 in string
{
char a = number2.charAt(j); // sets char to the next "letter"
if (a == '7' && oneSeven != true) // if the number is a 7 and there isnt already a seven
{
oneSeven = true; // now there is a seven,
for (int k = j + 1; k <= length; k++) // checks from the next char up to the length for a 9
{
char b = number2.charAt(k);
if (b == '9') {
sevNine = true;
}
}
} else if (a == '9' && oneNine != true) {
oneNine = true;
for (int l = j + 1; l <= length; l++) {
char b = number2.charAt(l);
if (b == '7') {
sevNine = true;
}
}
}
if (sevNine == true) {
counter++;
sevNine = false;
System.out.println(number2);
break;
}
}
}
System.out.println(counter);
}
If you run with the break statement, you should get 199262 as the resulting number.
I am given a string S and I have to make it a palindrome by re-arranging the characters of the given string.
If the given string can not be converted into a palindrome by re-arranging characters, print false and if it is possible to make it a palindrome, print true
My code:
String a=new String(br.readLine()); //given string
int n= a.length();
int j=0,k=n-1,count=0;
boolean flag=false;
for(int i=0;i<n;i++)
{
if(a.charAt(i)=='*')
continue; //for skipping already shifted chars
int ix = a.indexOf(a.charAt(i), i+1);
if(ix >= 0)
{ a=a.substring(0,i+1)+a.substring(i+1, ix) + "*" + a.substring(ix+1);
}
else
{
count++; //number of unique chars which can only be 1 or 0
if(count<=1 && n%2==1)
{
a=a.replaceFirst(a.substring(i,i+1),"*"); //giving middle position to the only unique char at center and replacing it with *
}
else
{
System.out.println("false"); //if more than one unique char, palindrome not possible
flag=true; // shows not possible
break;
}
}
}
if(!flag) // if possible
{
System.out.println("true");
}
One obvious optimization would replace:
if(a.substring(i+1).contains(a.substring(i,i+1)))
{
ans[j++]=i; //storing new positions in ans array
ans[k--]=a.substring(i+1).indexOf(a.charAt(i))+1+i;
a=a.substring(0,i+1)+a.substring(i+1).replaceFirst(a.substring(i,i+1),"*"); //replacing the shifted char with *
}
with:
int ix = a.indexOf(a.charAt(i), i+1);
if(ix >= 0)
{
ans[j++]=i; //storing new positions in ans array
ans[k--]=ix;
a=a.substring(0,i+1)+a.substring(i+1, ix) + "*" + a.substring(ix+1);
}
UPDATE
I wonder if the following code would be faster. There is no indexOf on arrays, so I had to do a loop, but there is no string manipulation:
char[] c = a.toCharArray();
int n= c.length;
int ans[]=new int[n]; // for storing new positions after shifting
int j=0,k=n-1,count=0;
boolean flag=false;
for(int i=0; i < n; i++)
{
char ch = c[i];
if(ch=='*')
continue; //for skipping already shifted chars
int ix = i;
do {
++ix;
} while (ix < n && c[ix] != ch);
if(ix < n)
{
ans[j++]=i;
ans[k--]=ix;
c[ix] = '*';
}
else
{
count++; //number of unique chars which can only be 1 or 0
if(count<=1 && n%2==1)
{
ans[(int)n/2]=i;
c[i] = '*';
}
else
{
System.out.println("-1"); //if more than one unique char, palindrome not possible
flag=true; // shows not possible
break;
}
}
}
UPDATE 2
You can also stop when j has reached n/2:
char[] c = a.toCharArray();
int n= c.length;
int ans[]=new int[n]; // for storing new positions after shifting
int j=0,k=n-1,count=0,half=n/2;
boolean flag=false;
for(int i=0; i < n; i++)
{
char ch = c[i];
if(ch=='*')
continue; //for skipping already shifted chars
int ix = i;
do {
++ix;
} while (ix < n && c[ix] != ch);
if(ix < n)
{
ans[j++]=i;
ans[k--]=ix;
c[ix] = '*';
if (j > half) {
break;
}
}
else
{
count++; //number of unique chars which can only be 1 or 0
if(count<=1 && n%2==1)
{
ans[half]=i;
c[i] = '*';
}
else
{
System.out.println("-1"); //if more than one unique char, palindrome not possible
flag=true; // shows not possible
break;
}
}
}
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
I'm writing a code to read a string and count sets of repeating
public int countRepeatedCharacters()
{
int c = 0;
for (int i = 1; i < word.length() - 1; i++)
{
if (word.charAt(i) == word.charAt(i + 1)) // found a repetition
{
if ( word.charAt(i - 1) != word.charAt(i)) {
c++;
}
}
}
return c;
}
If I try the input
aabbcdaaaabb
I should have 4 sets of repeat decimals
aa | bb | aaaa | bb
and I know I'm not reading the first set aa because my index starts at 1. I tried fixing it around to read zero but then I tr to fix the entire loop to work with the change and I failed, is there any advice as to how to change my index or loop?
Try this code:
public int countRepeatedCharacters(String word)
{
int c = 0;
Character last = null;
bool counted = false;
for (int i = 0; i < word.length(); i++)
{
if (last != null && last.equals(word.charAt(i))) { // same as previous characted
if (!counted) { // if not counted this character yet, count it
c++;
counted = true;
}
}
else { // new char, so update last and reset counted to false
last = word.charAt(i);
counted = false
}
}
return c;
}
Edit - counted aaaa as 4, fixed to count as 1
from what I understood from your question, you want to count number of repeating sets, then this should help.
for (int i = 0; i < word.length()-1; i++){
if (word.charAt(i) == word.charAt(i + 1)){ // found a repetition
if (i==0 || word.charAt(i - 1) != word.charAt(i)) {
c++;
}
}
}
Try this----
public int countRepeatedCharacters()
{
int c = 0,x=0;
boolean charMatched=false;
for (int i = 0; i < word.length(); i++)
{
if(i==word.length()-1)
{
if (word.charAt(i-1) == word.charAt(i))
c++;
break;
}
if (word.charAt(i) == word.charAt(i + 1)) // found a repetition
{
charMatched=true;
continue;
}
if(charMatched==true)
c++;
charMatched=false;
}
return c;
}
Try this method. It counts the sets of repeating charactors.
public static void main(String[] args) {
String word = "aabbcdaaaabbc";
int c = 0;
for (int i = 0; i < word.length()-1; i++) {
// found a repetition
if (word.charAt(i) == word.charAt(i + 1)) {
int k = 0;
while((i + k + 1) < word.length()) {
if(word.charAt(i+k) == word.charAt(i + k + 1)) {
k++;
continue;
}
else {
break;
}
}
c++;
i+=k-1;
}
}
System.out.println(c);
}
You can try something like this:-
public static void main(String str[]) {
String word = "aabbcdaaaabbc";
int c = 1;
for (int i = 0; i < word.length() - 1; i++) {
if (word.charAt(i) == word.charAt(i + 1)) {
c++;
} else {
System.out.println(word.charAt(i)+ " = " +c);
c = 1;
}
}
System.out.println(word.charAt(word.length()-1)+ " = " +c);
}
You can modify this as per your needs, by removing the sysouts and other stuffs.
Using length() -1 is causing you to not consider the last character in your calculations.
This is causing you to lose the last repetitive character.
Finally, I would have done this as follows:
public static int countRepeatedCharacters(String word)
{
boolean withinRepeating = false;
int c = 0;
for (int i = 1; i < word.length(); i++)
{
if (!withinRepeating && (withinRepeating = word.charAt(i) == word.charAt(i - 1)))
c++;
else
withinRepeating = word.charAt(i) == word.charAt(i - 1);
}
return c;
}