How can I write a method that will check if the letters in a string are all the same?
Show older comments
public boolean allSameLetter(String str) {
}
Answers (4)
Geoff Hayes
on 2 Dec 2015
George - use the unique function to find the unique characters in the string. If there is only one unique character then you know that all letters are the same
function [bAllSame] = allSameLetter(str)
bAllSame = length(unique(str))==1;
Stephen23
on 2 Dec 2015
Using diff would be much faster than unique:
>> str = 'aba';
>> any(diff(+str))
ans = 1
>> str = 'aaa';
>> any(diff(+str))
ans = 0
Image Analyst
on 2 Dec 2015
Another way is to use the diff function:
allTheSame = all(diff(str)==0)
Walter Roberson
on 2 Dec 2015
0 votes
First you have to show us your String class. MATLAB does not have a String class.
It looks to me that you are asking homework questions about a different programming language.
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!