Determine if a string has all the same characters: Difference between revisions

Line 1,592:
 
=={{header|Java}}==
<syntaxhighlight lang="java">
import java.util.regex.Matcher;
import java.util.regex.Pattern;
</syntaxhighlight>
<syntaxhighlight lang="java">
public static void main(String[] args) {
String[] strings = {
"", " ", "2", "333", ".55", "tttTTT", "5", "4444 444k"
};
for (String string : strings)
System.out.println(printCompare(string));
}
 
static String printCompare(String string) {
String stringA = "'%s' %d".formatted(string, string.length());
Pattern pattern = Pattern.compile("(.)\\1*");
Matcher matcher = pattern.matcher(string);
StringBuilder stringB = new StringBuilder();
/* 'Matcher' works dynamically, so we'll have to denote a change */
boolean difference = false;
char character;
String newline = System.lineSeparator();
while (matcher.find()) {
if (matcher.start() != 0) {
character = matcher.group(1).charAt(0);
stringB.append(newline);
stringB.append(" Char '%s' (0x%x)".formatted(character, (int) character));
stringB.append(" @ index %d".formatted(matcher.start()));
difference = true;
}
}
if (!difference)
stringB.append(newline).append(" All characters are the same");
return stringA + stringB;
}
</syntaxhighlight>
<pre>
'' 0
All characters are the same
' ' 3
All characters are the same
'2' 1
All characters are the same
'333' 3
All characters are the same
'.55' 3
Char '5' (0x35) @ index 1
'tttTTT' 6
Char 'T' (0x54) @ index 3
'5' 1
All characters are the same
'4444 444k' 9
Char ' ' (0x20) @ index 4
Char '4' (0x34) @ index 5
Char 'k' (0x6b) @ index 8
</pre>
<br />
Alternate implementations
<syntaxhighlight lang="java">public class Main{
public static void main(String[] args){
118

edits