Trying to return true if all the letters in a string are the same
Solution 1
Using regex:
return str.matches("^(.)\\1*$");
Using streams:
str.chars().allMatch(c -> c == str.charAt(0));
Other:
return str.replace(String.valueOf(str.charAt(0), "").length() == 0;
Solution 2
You can follow the below steps:
(1) Get the first character (i.e., 0th index)
(2) Check the first character is the same with subsequent characters, if not return false
(and comes out from method)
(3) If all chars match i.e., processing goes till the end of the method and returns true
public boolean allSameLetter(String str) {
char c1 = str.charAt(0);
for(int i=1;i<str.length;i++) {
char temp = str.charAt(i);
if(c1 != temp) {
//if chars does NOT match,
//just return false from here itself,
//there is no need to verify other chars
return false;
}
}
//As it did NOT return from above if (inside for)
//it means, all chars matched, so return true
return true;
}
Solution 3
As Andrew said, you are decreasing i
within your for loop. You can fix this by changing it to int charb4 = i - 1;
. As for making your code more efficient you could condense it down to this.
public boolean allSameLetter(String str) {
for(char c : str.toCharArray())
if(c != str.charAt(0)) return false;
return true;
}
Solution 4
Comment if you don't understand a part of it :)
public boolean allSameLetter(String str)
{
for (int i = 1; i < str.length() -1; i++)
{
if ( str.charAt(i) != str.charAt(i+1))
{
return false;
}
}
return true
}
-1 is there since I am checking the current value in the array, then the next value in the array, thus I need to stop a place earlier.
If the loop if statement is never entered, it will make it far enough into the code to return true
Harry You
Updated on June 07, 2022Comments
-
Harry You almost 2 years
What I have so far:
public boolean allSameLetter(String str) { for (int i = 1; i < str.length(); i++) { int charb4 = i--; if ( str.charAt(i) != str.charAt(charb4)) { return false; } if ( i == str.length()) { return true; } } }
Please excuse any inefficiencies if any; still relatively new to coding in general. Am I lacking some knowledge in terms of using operators and .charAt() together? Is it illogical? Or is my error elsewhere?
-
Gabriel Stellini over 7 yearsIt can be made more efficiently, but I chose to keep your code in order to help you. No problem :)
-
SaiyanGirl about 5 yearsCould you explain that first regex please?
-
LowKeyEnergy over 4 yearsAn explanation would be helpful. Also, your answer does not appear to match the asker's skill level.