Jump to content

Determine if a string has all the same characters

From Rosetta Code
Task
Determine if a string has all the same characters
You are encouraged to solve this task according to the task description, using any language you may know.
Task

Given a character string   (which may be empty, or have a length of zero characters):

  •   create a function/procedure/routine to:
  •   determine if all the characters in the string are the same
  •   indicate if or which character is different from the previous character
  •   display each string and its length   (as the strings are being examined)
  •   a zero─length (empty) string shall be considered as all the same character(s)
  •   process the strings from left─to─right
  •   if       all the same character,   display a message saying such
  •   if not all the same character,   then:
  •   display a message saying such
  •   display what character is different
  •   only the 1st different character need be displayed
  •   display where the different character is in the string
  •   the above messages can be part of a single message
  •   display the hexadecimal value of the different character


Use (at least) these seven test values   (strings):

  •   a string of length   0   (an empty string)
  •   a string of length   3   which contains three blanks
  •   a string of length   1   which contains:   2
  •   a string of length   3   which contains:   333
  •   a string of length   3   which contains:   .55
  •   a string of length   6   which contains:   tttTTT
  •   a string of length   9   with a blank in the middle:   4444   444k


Show all output here on this page.

Other tasks related to string operations:
Metrics
Counting
Remove/replace
Anagrams/Derangements/shuffling
Find/Search/Determine
Formatting
Song lyrics/poems/Mad Libs/phrases
Tokenize
Sequences



11l

Translation of: Kotlin
F analyze(s)
   print(‘Examining [’s‘] which has a length of ’s.len‘:’)
   I s.len > 1
      V b = s[0]
      L(c) s
         V i = L.index
         I c != b
            print(‘    Not all characters in the string are the same.’)
            print(‘    '’c‘' (0x’hex(c.code)‘) is different at position ’i)
            R

   print(‘    All characters in the string are the same.’)

V strs = [‘’, ‘   ’, ‘2’, ‘333’, ‘.55’, ‘tttTTT’, ‘4444 444k’]
L(s) strs
   analyze(s)
Output:
Examining [] which has a length of 0:
    All characters in the string are the same.
Examining [   ] which has a length of 3:
    All characters in the string are the same.
Examining [2] which has a length of 1:
    All characters in the string are the same.
Examining [333] which has a length of 3:
    All characters in the string are the same.
Examining [.55] which has a length of 3:
    Not all characters in the string are the same.
    '5' (0x35) is different at position 1
Examining [tttTTT] which has a length of 6:
    Not all characters in the string are the same.
    'T' (0x54) is different at position 3
Examining [4444 444k] which has a length of 9:
    Not all characters in the string are the same.
    ' ' (0x20) is different at position 4

Action!

PROC PrintBH(BYTE a)
  BYTE ARRAY hex=['0 '1 '2 '3 '4 '5 '6 '7 '8 '9 'A 'B 'C 'D 'E 'F]

  Put(hex(a RSH 4))
  Put(hex(a&$0F))
RETURN

PROC Test(CHAR ARRAY s)
  BYTE i,pos

  pos=0
  FOR i=2 TO s(0)
  DO
    IF s(i)#s(1) THEN
      pos=i 
      EXIT
    FI
  OD

  PrintF("""%S"" (len=%B) -> ",s,s(0))
  IF pos=0 THEN
    PrintE("all characters are the same.")
  ELSE
    PrintF("""%C"" (hex=$",s(pos))
    PrintBH(s(pos))
    PrintF(") is the first difference at pos. %B.%E",pos)
  FI
  PutE()
RETURN

PROC Main()
  Test("")
  Test("   ")
  Test("2")
  Test("333")
  Test(".55")
  Test("tttTTT")
  Test("4444 444k")
RETURN
Output:

Screenshot from Atari 8-bit computer

"" (len=0) -> all characters are the same.

"   " (len=3) -> all characters are the same.

"2" (len=1) -> all characters are the same.

"333" (len=3) -> all characters are the same.

".55" (len=3) -> "5" (hex=$35) is the first difference at pos. 2.

"tttTTT" (len=6) -> "T" (hex=$54) is the first difference at pos. 4.

"4444 444k" (len=9) -> " " (hex=$20) is the first difference at pos. 5.

Ada

with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_All_Chars_Are_Same is
   procedure All_Chars_Are_Same (S : in String) is
      First_Diff : Natural := 0;
   begin
      Put_Line ("Input = """ & S & """, length =" & S'Length'Image);
      for I in S'First + 1 .. S'Last loop
         if S(I) /= S(S'First) then
            First_Diff := I;
            exit;
         end if;
      end loop;
      if First_Diff = 0 then
         Put_Line (" All characters are the same.");
      else
         Put (" First difference at position" & First_Diff'Image &
              ", character = '" & S(First_Diff) &
              "', hex = ");
         Put (Character'Pos (S(First_Diff)), Width => 0, Base => 16);
         New_Line;
      end if;
   end All_Chars_Are_Same;
begin
   All_Chars_Are_Same ("");
   All_Chars_Are_Same ("   ");
   All_Chars_Are_Same ("2");
   All_Chars_Are_Same ("333");
   All_Chars_Are_Same (".55");
   All_Chars_Are_Same ("tttTTT");
   All_Chars_Are_Same ("4444 444k");
end Test_All_Chars_Are_Same;
Output:
Input = "", length = 0
 All characters are the same.
Input = "   ", length = 3
 All characters are the same.
Input = "2", length = 1
 All characters are the same.
Input = "333", length = 3
 All characters are the same.
Input = ".55", length = 3
 First difference at position 2, character = '5', hex = 16#35#
Input = "tttTTT", length = 6
 First difference at position 4, character = 'T', hex = 16#54#
Input = "4444 444k", length = 9
 First difference at position 5, character = ' ', hex = 16#20#

ALGOL 68

BEGIN
    # return the position of the first different character in s           #
    #     or UPB s + 1 if all the characters are the same                 #
    OP  FIRSTDIFF = ( STRING s )INT:
        IF UPB s <= LWB s
        THEN
            # 0 or 1 character                                            #
            UPB s + 1
        ELSE
            # two or more characters                                      #
            INT  result := LWB s + 1;
            CHAR c1      = s[ LWB s ];
            FOR s pos FROM LWB s + 1 TO UPB s WHILE s[ s pos ] = c1 DO result +:= 1 OD;
            result
        FI # FIRSTDIFF # ;
    # convert a character to a hex string                                 #
    PROC hex = ( CHAR c )STRING:
        BEGIN
            STRING result := "";
            INT    n      := ABS c;
            IF n = 0
            THEN
                result := "0"
            ELSE
                WHILE n > 0 DO
                    INT d = n MOD 16;
                    n OVERAB 16;
                    IF d < 10
                    THEN REPR ( d + ABS "0" )
                    ELSE REPR ( ( d - 10 ) + ABS "a" )
                    FI +=: result
                OD
            FI;
            result
        END # hex # ;
    # show whether s contains all the same character of the first diff    #
    PROC show first diff = ( STRING s )VOID:
        IF  print( ( """", s, """ (length ", whole( ( UPB s + 1 ) - LWB s, 0 ), "): " ) );
            INT diff pos = FIRSTDIFF s;
            diff pos > UPB s
        THEN
            # all characters the same                                     #
            print( ( "all characters are the same", newline ) )
        ELSE
            # not all characters are the same                             #
            print( ( "first different character """
                   , s[ diff pos ]
                   , """(0x", hex( s[ diff pos ] )
                   , ") at position: "
                   , whole( diff pos, 0 )
                   , newline
                   )
                 )
        FI # show first diff # ;
    # task test cases                                                     #
    show first diff( ""          );
    show first diff( "   "       );
    show first diff( "2"         );
    show first diff( "333"       );
    show first diff( ".55"       );
    show first diff( "tttTTT"    );
    show first diff( "4444 444k" );
    show first diff( "4444|444k" )
END
Output:
"" (length 0): all characters are the same
"   " (length 3): all characters are the same
"2" (length 1): all characters are the same
"333" (length 3): all characters are the same
".55" (length 3): first different character "5"(0x35) at position: 2
"tttTTT" (length 6): first different character "T"(0x54) at position: 4
"4444 444k" (length 9): first different character " "(0x20) at position: 5
"4444|444k" (length 9): first different character "|"(0x7c) at position: 5

Arturo

strings: [
    "", "   ", "2", "333", ".55", "tttTTT", 
    "4444   444k", "pépé", "🐶🐶🐺🐶", "🎄🎄🎄🎄"
]

allSameChars?: function [str][
    if empty? str -> return ø
    current: first str
    loop.with:'i str 'ch [
        if ch <> current -> return i
    ]
    return ø
]

loop strings 's [
    prints ["\"" ++ s ++ "\"" ~"(size |size s|):"]
    firstNotSame: allSameChars? s
    if? null? firstNotSame -> print "all the same."
    else -> print ~"first different char `|get s firstNotSame|` at position |firstNotSame|."
]
Output:
"" (size 0): all the same.
"   " (size 3): all the same.
"2" (size 1): all the same.
"333" (size 3): all the same.
".55" (size 3): first different char `5` at position 1.
"tttTTT" (size 6): first different char `T` at position 3.
"4444   444k" (size 11): first different char ` ` at position 4.
"pépé" (size 4): first different char `é` at position 1.
"🐶🐶🐺🐶" (size 4): first different char `🐺` at position 2.
"🎄🎄🎄🎄" (size 4): all the same.

AutoHotkey

testCases := ["", "   ", "2", "333", ".55", "tttTTT", "4444 4444k"]
for key, str in testCases {
	MsgBox % "Examining `'" str "`' which has a length of " StrLen(str) ":`n"
	if (StrLen(str) == 0) or (StrLen(str) == 1) {
		MsgBox % "  All characters in the string are the same.`n"
		continue
	}
	firstChar := SubStr(str, 1, 1)
	Loop, Parse, str 
	{
		if (firstChar != A_LoopField) {
			hex := Format("0x{:x}", Ord(A_LoopField))
			MsgBox % "  Not all characters in the string are the same.`n  Character `'" A_LoopField "`' (" hex ") is different at position " A_Index ".`n", *
			break
		}
		if (A_Index = StrLen(str))
			MsgBox % "  All characters in the string are the same.`n", *
	}
}
Output:
Examining '' which has a length of 0:
    All characters in the string are the same.
Examining '   ' which has a length of 3:
    All characters in the string are the same.
Examining '2' which has a length of 1:
    All characters in the string are the same.
Examining '333' which has a length of 3:
    All characters in the string are the same.
Examining '.55' which has a length of 3:
    Not all characters in the string are the same.
    Character '5' (0x35) is different at position 2.
Examining 'tttTTT' which has a length of 6:
    All characters in the string are the same.
Examining '4444 4444k' which has a length of 10:
    Not all characters in the string are the same.
    Character ' ' (0x20) is different at position 5.

AWK

# syntax: GAWK -f DETERMINE_IF_A_STRING_HAS_ALL_THE_SAME_CHARACTERS.AWK
BEGIN {
    for (i=0; i<=255; i++) { ord_arr[sprintf("%c",i)] = i } # build array[character]=ordinal_value
    n = split(",   ,2,333,.55,tttTTT,4444 444k",arr,",")
    for (i in arr) {
      width = max(width,length(arr[i]))
    }
    width += 2
    fmt = "| %-*s | %-6s | %-8s | %-8s | %-3s | %-8s |\n"
    head1 = head2 = sprintf(fmt,width,"string","length","all same","1st diff","hex","position")
    gsub(/[^|\n]/,"-",head1)
    printf(head1 head2 head1) # column headings
    for (i=1; i<=n; i++) {
      main(arr[i])
    }
    printf(head1) # column footing
    exit(0)
}
function main(str,  c,first_diff,hex,i,leng,msg,position) {
    msg = "yes"
    leng = length(str)
    for (i=1; i<leng; i++) {
      c = substr(str,i+1,1)
      if (substr(str,i,1) != c) {
        msg = "no"
        first_diff = "'" c "'"
        hex = sprintf("%2X",ord_arr[c])
        position = i + 1
        break
      }
    }
    printf(fmt,width,"'" str "'",leng,msg,first_diff,hex,position)
}
function max(x,y) { return((x > y) ? x : y) }
Output:
|-------------|--------|----------|----------|-----|----------|
| string      | length | all same | 1st diff | hex | position |
|-------------|--------|----------|----------|-----|----------|
| ''          | 0      | yes      |          |     |          |
| '   '       | 3      | yes      |          |     |          |
| '2'         | 1      | yes      |          |     |          |
| '333'       | 3      | yes      |          |     |          |
| '.55'       | 3      | no       | '5'      | 35  | 2        |
| 'tttTTT'    | 6      | no       | 'T'      | 54  | 4        |
| '4444 444k' | 9      | no       | ' '      | 20  | 5        |
|-------------|--------|----------|----------|-----|----------|

BASIC

Applesoft BASIC

 10  DATA "","   ","2","333",".55","tttTTT","4444 444k"
 20  LET Q$ =  CHR$ (34)
 30  HOME 
 40  FOR E = 1 TO 7
 50      READ S$
 60      GOSUB 100
 70      PRINT O$" IN"M$Q$S$Q$" OF LENGTH "L".";
 80  NEXT E
 90  END 
 100  GOSUB 200
 110  PRINT M$M$;
 120  LET M$ =  CHR$ (13)
 130  LET O$ = "ALL OF THE CHARACTERS ARE THE SAME"
 140  IF SAME THEN  RETURN 
 150  PRINT "THE FIRST DIFFERENT CHARACTER IS"
 160  PRINT  TAB( I)Q$C$Q$;
 170  PRINT " ASCII " ASC (C$)" AT POSITION ";
 180  LET O$ =  STR$ (I)
 190  RETURN 
 200  LET C$ =  LEFT$ (S$,1)
 210  LET L =  LEN (S$)
 220  FOR I = 1 TO L
 230      IF C$ =  MID$ (S$,I,1) THEN  NEXT I
 240  LET C$ =  MID$ (S$,I,1)
 250  LET SAME = C$ = ""
 260  RETURN
Output:
ALL OF THE CHARACTERS ARE THE SAME IN
"" OF LENGTH 0.

ALL OF THE CHARACTERS ARE THE SAME IN
"   " OF LENGTH 3.

ALL OF THE CHARACTERS ARE THE SAME IN
"2" OF LENGTH 1.

ALL OF THE CHARACTERS ARE THE SAME IN
"333" OF LENGTH 3.

THE FIRST DIFFERENT CHARACTER IS
 "5" ASCII 53 AT POSITION 2 IN
".55" OF LENGTH 3.

THE FIRST DIFFERENT CHARACTER IS
   "T" ASCII 84 AT POSITION 4 IN
"tttTTT" OF LENGTH 6.

THE FIRST DIFFERENT CHARACTER IS
    " " ASCII 32 AT POSITION 5 IN
"4444 444k" OF LENGTH 9.

BASIC256

call CaracteresUnicos("")
call CaracteresUnicos(".")
call CaracteresUnicos("abcABC")
call CaracteresUnicos("XYZ ZYX")
call CaracteresUnicos("1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ")
end

subroutine CaracteresUnicos (cad$)
	lngt = length(cad$)
	print 'String = "'; cad$; '", length = '; lngt
	for i = 1 to lngt
		for j = i + 1 to lngt
			if mid(cad$,i,1) = mid(cad$,j,1) then
				print " First difference at position " & i & " and " & j & ", character = '" &  mid(cad$,i,1) & "', hex value = " & tohex(asc(mid(cad$,i,1)))
				return
			end if
		next j
	next i
	print " All characters are the same." & chr(10)
end subroutine
Output:
String = "", length =  0
 All characters are the same.

String = ".", length =  1
 All characters are the same.

String = "abcABC", length =  6
 All characters are the same.

String = "XYZ ZYX", length =  7
 First difference at position 1 and 7, character = 'X', hex value = 58

String = "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ", length =  36
 First difference at position 10 and 25, character = '0', hex value = 30

Chipmunk Basic

Works with: Chipmunk Basic version 3.6.4

The GW-BASIC solution works without any changes.

Gambas

Public Sub CaracteresUnicos(cad As String) 

  Dim lngt As Integer = Len(cad) 
  Dim i, j As Integer  
  
  Print "String = \"" & cad & "\", length = " & lngt  
  
  For i = 1 To lngt 
    For j = i + 1 To lngt 
      If Mid(cad, i, 1) = Mid(cad, j, 1) Then 
        Print " First difference at position " & i & " and " & j & ", character = '" & Mid(cad, i, 1) & "', hex value = " & Hex(Asc(Mid(cad, i, 1))) 
        Print 
        Return
      End If 
    Next
  Next
  Print " All characters are the same.\n"
  
End Sub

Public Sub Main()
  
  CaracteresUnicos("") 
  CaracteresUnicos(".") 
  CaracteresUnicos("abcABC") 
  CaracteresUnicos("XYZ ZYX") 
  CaracteresUnicos("1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ")
  
End
Output:
String = "", length =  0
 All characters are the same.

String = ".", length =  1
 All characters are the same.

String = "abcABC", length =  6
 All characters are the same.

String = "XYZ ZYX", length =  7
 First difference at position 1 and 7, character = 'X', hex value = 58

String = "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ", length =  36
 First difference at position 10 and 25, character = '0', hex value = 30

GW-BASIC

Works with: BASICA
Works with: PC-BASIC version any
Works with: Chipmunk Basic version 3.6.4
10 'SAVE"SAMECHAR", A
20 DEFINT A-Z
30 DATA "","   ","2","333",".55","tttTTT","4444 444k", "FIN"
40 ' Main program cycle
50 CLS
60 PRINT "Program SameChar"
70 PRINT "Determines if a string has the same character or not."
80 PRINT
90 WHILE S$<>"FIN"
100   READ S$
110   IF S$="FIN" THEN 150
120   GOSUB 190  ' Revision subroutine
130   PRINT "'";S$;"' of length";LEN(S$);
140   IF I<2 THEN PRINT "contains all the same character." ELSE PRINT "is different at possition";STR$(I);": '";DC$; "' (0x"; HEX$(ASC(DC$)); ")"
150 WEND
160 PRINT
170 PRINT "End of program run."
180 END
190 ' DifChar subroutine
200   C$ = LEFT$(S$,1)
210   I = 1
220   DC$=""
230   WHILE I<LEN(S$) AND DC$=""
240     IF MID$(S$,I,1)<>C$ THEN DC$=MID$(S$,I,1) ELSE I=I+1
250   WEND
260   IF DC$="" THEN I=1
270 RETURN
Output:
Program SameChar
Determines if a string has the same character or not.

'' of length 0 contains all the same character.
'   ' of length 3 contains all the same character.
'2' of length 1 contains all the same character.
'333' of lenght 3 contains all the same character.
'.55' of length 3 is different at possition 2: '5' (0x35)
'tttTTT' of length 6 is different at possition 4: 'T' (0x54)
'4444 444k' of length 9 is different at possition 5: ' ' (0x20)

End of program run.

IS-BASIC

100 PROGRAM "Samechar.bas"
110 DO
120   READ IF MISSING EXIT DO:TEST$
130   LET TEST=SAMEC(TEST$)
140   PRINT """";TEST$;""" (length =";LEN(TEST$);")"
150   IF NOT TEST THEN
160     PRINT "All characters are the same"
170   ELSE
180     PRINT """";TEST$(TEST);""" is the first difference at pos.";TEST
190   END IF
200   PRINT
210 LOOP 
220 DEF SAMEC(S$)
230   LET SAMEC=0
240   IF LEN(S$)>1 THEN
250     FOR I=2 TO LEN(S$)
260       IF S$(I)<>S$(1) THEN LET SAMEC=I:EXIT FOR
270     NEXT
280   END IF
290 END DEF
300 DATA "","   ",2,333,.55,tttTTT,"4444 444k"

OxygenBasic

uses console

sub CaracteresUnicos (cad as string)
    int i, j, lngt
    lngt = len(cad)
    printl "String = " chr(34) & cad & chr(34) ", length = " lngt
    for i = 1 to lngt
        for j = i + 1 to lngt
            if mid(cad,i,1) = mid(cad,j,1) then
                printl " First difference at position " & i & _
                " and " & j & ", character = '" &  mid(cad,i,1) & _
                "', hex value = " & hex(asc(mid(cad,i,1)))
                printl
                exit sub
            end if
        next j
    next i
    printl " All characters are the same." cr
end sub

CaracteresUnicos ("")
CaracteresUnicos (".")
CaracteresUnicos ("abcABC")
CaracteresUnicos ("XYZ ZYX")
CaracteresUnicos ("1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ")

printl cr "Enter ..."
waitkey

PureBasic

Procedure CaracteresUnicos(cad.s)   
  lngt.i = Len(cad) 
  PrintN("String = '" + cad + "' length = " + Str(lngt))
  For i.i = 1 To lngt 
    For j.i = i + 1 To lngt 
      If Mid(cad, i, 1) = Mid(cad, j, 1)
        PrintN(" First difference at position " + Str(i) + " and " + Str(j) + ", character = '"  + Mid(cad, i, 1) + "', hex value = "  + Hex(Asc(Mid(cad, i, 1))) + #CRLF$)
        ProcedureReturn
      EndIf 
    Next
  Next
  PrintN(" All characters are the same." + #CRLF$)
EndProcedure

OpenConsole()
CaracteresUnicos("") 
CaracteresUnicos(".") 
CaracteresUnicos("abcABC") 
CaracteresUnicos("XYZ ZYX") 
CaracteresUnicos("1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ")
PrintN(#CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()

QBasic

The QB64 solution works without any changes.

QB64

Works with: QBasic version 1.1
DECLARE Sub CaracteresUnicos (cad$)

CaracteresUnicos ("")
CaracteresUnicos (".")
CaracteresUnicos ("abcABC")
CaracteresUnicos ("XYZ ZYX")
CaracteresUnicos ("1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ")
End

Sub CaracteresUnicos (cad$)
    lngt = Len(cad$)
    Print "String = '"; cad$; "' length = "; lngt
    For i = 1 To lngt
        For j = i + 1 To lngt
            If Mid$(cad$, i, 1) = Mid$(cad$, j, 1) Then
                Print " First difference at position "; i; " and "; j; ", character = '"; Mid$(cad$, i, 1); "', hex value = "; Hex$(Asc(Mid$(cad$, i, 1)))
                Print
                Exit Sub
            End If
        Next j
    Next i
    Print " All characters are the same."; Chr$(10)
End Sub

QuickBASIC

Works with: QBasic
Works with: QB64
Works with: VB-DOS
Works with: PDS version 7.x
DECLARE SUB DifChar (sString AS STRING, wc AS INTEGER, dc AS STRING)

DIM i AS INTEGER
DIM s AS STRING
DIM dc AS STRING

DATA "", "   ",  "2", "333",".55","tttTTT", "4444 444k", "FIN"

' Main program cycle
CLS
PRINT "Program SameChar"
PRINT "Determines if a string has the same character or not."
PRINT
DO
  READ s
  IF s = "FIN" THEN EXIT DO
  DifChar s, i, dc
  PRINT "'"; s; "' of length"; LEN(s);
  IF i < 2 THEN
    PRINT "contains all the same character."
  ELSE
    PRINT "is different at possition"; STR$(i); ": '"; dc; "' (0x"; HEX$(ASC(dc)); ")"
  END IF
LOOP
PRINT
PRINT "End of program run."
END

SUB DifChar (sString AS STRING, wc AS INTEGER, dc AS STRING)
  ' Var
  DIM c AS STRING

  ' Look for the distinct char
  c = LEFT$(sString, 1)
  wc = 1
  dc = ""
  DO WHILE wc < LEN(sString)
    IF MID$(sString, wc, 1) <> c THEN dc = MID$(sString, wc, 1): EXIT DO
    wc = wc + 1
  LOOP

  IF dc = "" THEN wc = 1
END SUB
Output:
Program SameChar
Determines if a string has the same character or not.

'' of length 0 contains all the same character.
'   ' of length 3 contains all the same character.
'2' of length 1 contains all the same character.
'333' of lenght 3 contains all the same character.
'.55' of length 3 is different at possition 2: '5' (0x35)
'tttTTT' of length 6 is different at possition 4: 'T' (0x54)
'4444 444k' of length 9 is different at possition 5: ' ' (0x20)

End of program run.

Yabasic

caracteresunicos ("")
caracteresunicos (".")
caracteresunicos ("abcABC")
caracteresunicos ("XYZ ZYX")
caracteresunicos ("1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ")
end

sub caracteresunicos (cad$)
    local lngt, i, j
    
	lngt = len(cad$)
    print "cadena = \"", cad$, "\", length = ", lngt
    for i = 1 to lngt
        for j = i + 1 to lngt
            if mid$(cad$,i,1) = mid$(cad$,j,1) then
                print " First difference at position ", i, " and ", j, ", character = \'",  mid$(cad$,i,1), "\', hex value = ", hex$(asc(mid$(cad$,i,1)))
                print
                return
            end if
        next j
    next i
    print " All characters are the same.\n"
end sub

BCPL

get "libhdr"

let diffchar(s) = valof
$(  for i=2 to s%0
        unless s%i = s%1 resultis i
    resultis 0
$)

let show(s) be
$(  let i = diffchar(s)
    writef("*"%S*" (length %N): ", s, s%0)
    test i=0
        do writes("all the same.*N")
        or writef("'%C' at index %N.*N", s%i, i)
$)

let start() be
$(  show("")
    show("   ")
    show("2")
    show("333")
    show(".55")
    show("tttTTT")
    show("4444 444k")
$)
Output:
"" (length 0): all the same.
"   " (length 3): all the same.
"2" (length 1): all the same.
"333" (length 3): all the same.
".55" (length 3): '5' at index 2.
"tttTTT" (length 6): 'T' at index 4.
"4444 444k" (length 9): ' ' at index 5.

BQN

Hex function is pieced together from BQNcrate idioms.

Check=´˘2
Hex("0A"+¨1026)16{𝕗|⌊÷𝕗(1+·𝕗1⌈⊢)}

{
  𝕊 str:
  rCheck 2(0=≠)str
  •Out {
    ´r ? "All characters are the same" ;
    ir0
    ch(i+1)str
    "'"ch"' (hex: "(Hex ch-@)", index: "(•Fmt i)") mismatched in string '"str"'"
  }  
}¨
  ""
  "   "
  "2"
  "333"
  ".55"
  "tttTTT"
  "4444   444k"

All characters are the same
All characters are the same
All characters are the same
All characters are the same
'5' (hex: 35, index: 0) mismatched in string '.55'
'T' (hex: 54, index: 2) mismatched in string 'tttTTT'
' ' (hex: 20, index: 3) mismatched in string '4444   444k'

C

Solution with an index to a table

In interactive mode, strings with spaces have to be enclosed in double quotes ("")

#include<string.h>
#include<stdio.h>

int main(int argc,char** argv)
{
    int i,len;
    char reference;
    
    if(argc>2){
        printf("Usage : %s <Test String>\n",argv[0]);
        return 0;
    }

    if(argc==1||strlen(argv[1])==1){
        printf("Input string : \"%s\"\nLength : %d\nAll characters are identical.\n",argc==1?"":argv[1],argc==1?0:(int)strlen(argv[1]));
        return 0;
    }

    reference = argv[1][0];
    len = strlen(argv[1]);

    for(i=1;i<len;i++){
        if(argv[1][i]!=reference){
            printf("Input string : \"%s\"\nLength : %d\nFirst different character : \"%c\"(0x%x) at position : %d\n",argv[1],len,argv[1][i],argv[1][i],i+1);
            return 0;
        }
    }

    printf("Input string : \"%s\"\nLength : %d\nAll characters are identical.\n",argv[1],len);

    return 0;

}

Output :

abhishek_ghosh@Azure:~/doodles$ ./a.out
Input string : ""
Length : 0
All characters are identical.
abhishek_ghosh@Azure:~/doodles$ ./a.out "   "
Input string : "   "
Length : 3
All characters are identical.
abhishek_ghosh@Azure:~/doodles$ ./a.out 2
Input string : "2"
Length : 1
All characters are identical.
abhishek_ghosh@Azure:~/doodles$ ./a.out 333
Input string : "333"
Length : 3
All characters are identical.
abhishek_ghosh@Azure:~/doodles$ ./a.out .55
Input string : ".55"
Length : 3
First different character : "5"(0x35) at position : 2
abhishek_ghosh@Azure:~/doodles$ ./a.out tttTTT
Input string : "tttTTT"
Length : 6
First different character : "T"(0x54) at position : 4
abhishek_ghosh@Azure:~/doodles$ ./a.out "4444 444k"
Input string : "4444 444k"
Length : 9
First different character : " "(0x20) at position : 5

Solution with pointers

/**
 * An example for RossetaCode - an example of string operation with wchar_t and
 * with old 8-bit characters. Anyway, it seem that C is not very UTF-8 friendly,
 * thus C# or C++ may be a better choice.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/*
 * The wide character version of the program is compiled if WIDE_CHAR is defined
 */
#define WIDE_CHAR

#ifdef WIDE_CHAR
#define CHAR wchar_t
#else
#define CHAR char
#endif

/**
 * Find a character different from the preceding characters in the given string.
 * 
 * @param s the given string, NULL terminated.
 * 
 * @return the pointer to the occurence of the different character 
 *         or a pointer to NULL if all characters in the string
 *         are exactly the same.
 * 
 * @notice This function return a pointer to NULL also for empty strings.
 *         Returning NULL-or-CHAR would not enable to compute the position
 *         of the non-matching character.
 * 
 * @warning This function compare characters (single-bytes, unicode etc.).
 *          Therefore this is not designed to compare bytes. The NULL character
 *          is always treated as the end-of-string marker, thus this function
 *          cannot be used to scan strings with NULL character inside string,
 *          for an example "aaa\0aaa\0\0".
 */
const CHAR* find_different_char(const CHAR* s)
{
    /* The code just below is almost the same regardles 
       char or wchar_t is used. */

    const CHAR c = *s;
    while (*s && c == *s)
    {
        s++;
    }
    return s;
}

/**
 * Apply find_different_char function to a given string and output the raport.
 * 
 * @param s the given NULL terminated string.
 */
void report_different_char(const CHAR* s)
{
#ifdef WIDE_CHAR
    wprintf(L"\n");
    wprintf(L"string: \"%s\"\n", s);
    wprintf(L"length: %d\n", wcslen(s));
    const CHAR* d = find_different_char(s);
    if (d)
    {
        /*
         * We have got the famous pointers arithmetics and we can compute
         * difference of pointers pointing to the same array.
         */
        wprintf(L"character '%wc' (%#x) at %d\n", *d, *d, (int)(d - s));
    }
    else
    {
        wprintf(L"all characters are the same\n");
    }
    wprintf(L"\n");
#else
    putchar('\n');
    printf("string: \"%s\"\n", s);
    printf("length: %d\n", strlen(s));
    const CHAR* d = find_different_char(s);
    if (d)
    { 
        /*
         * We have got the famous pointers arithmetics and we can compute
         * difference of pointers pointing to the same array.
         */
        printf("character '%c' (%#x) at %d\n", *d, *d, (int)(d - s));
    }
    else
    {
        printf("all characters are the same\n");
    }
    putchar('\n');
#endif
}

/* There is a wmain function as an entry point when argv[] points to wchar_t */

#ifdef WIDE_CHAR
int wmain(int argc, wchar_t* argv[])
#else
int main(int argc, char* argv[])
#endif
{
    if (argc < 2)
    {
        report_different_char(L"");
        report_different_char(L"   ");
        report_different_char(L"2");
        report_different_char(L"333");
        report_different_char(L".55");
        report_different_char(L"tttTTT");
        report_different_char(L"4444 444k");
    }
    else
    {
        report_different_char(argv[1]);
    }

    return EXIT_SUCCESS;
}
Output:
string: ""
length: 0
all characters are the same


string: "   "
length: 3
all characters are the same


string: "2"
length: 1
all characters are the same


string: "333"
length: 3
all characters are the same


string: ".55"
length: 3
character '5' (0x35) at 1


string: "tttTTT"
length: 6
character 'T' (0x54) at 3


string: "4444 444k"
length: 9
character ' ' (0x20) at 4

C#

Translation of: D
using System;

namespace AllSame {
    class Program {
        static void Analyze(string s) {
            Console.WriteLine("Examining [{0}] which has a length of {1}:", s, s.Length);
            if (s.Length > 1) {
                var b = s[0];
                for (int i = 1; i < s.Length; i++) {
                    var c = s[i];
                    if (c != b) {
                        Console.WriteLine("    Not all characters in the string are the same.");
                        Console.WriteLine("    '{0}' (0x{1:X02}) is different at position {2}", c, (int)c, i);
                        return;
                    }
                }

            }
            Console.WriteLine("    All characters in the string are the same.");
        }

        static void Main() {
            var strs = new string[] { "", "   ", "2", "333", ".55", "tttTTT", "4444 444k" };
            foreach (var str in strs) {
                Analyze(str);
            }
        }
    }
}
Output:
Examining [] which has a length of 0:
    All characters in the string are the same.
Examining [   ] which has a length of 3:
    All characters in the string are the same.
Examining [2] which has a length of 1:
    All characters in the string are the same.
Examining [333] which has a length of 3:
    All characters in the string are the same.
Examining [.55] which has a length of 3:
    Not all characters in the string are the same.
    '5' (0x35) is different at position 1
Examining [tttTTT] which has a length of 6:
    Not all characters in the string are the same.
    'T' (0x54) is different at position 3
Examining [4444 444k] which has a length of 9:
    Not all characters in the string are the same.
    ' ' (0x20) is different at position 4

C++

#include <iostream>
#include <string_view>

void all_characters_are_the_same(std::string_view str) {
    size_t len = str.length();
    std::cout << "input: \"" << str << "\", length: " << len << '\n';
    if (len > 0) {
        char ch = str[0];
        for (size_t i = 1; i < len; ++i) {
            if (str[i] != ch) {
                std::cout << "Not all characters are the same.\n";
                std::cout << "Character '" << str[i] << "' (hex " << std::hex
                          << static_cast<unsigned int>(str[i])
                          << ") at position " << std::dec << i + 1
                          << " is not the same as '" << ch << "'.\n\n";
                return;
            }
        }
    }
    std::cout << "All characters are the same.\n\n";
}

int main() {
    all_characters_are_the_same("");
    all_characters_are_the_same("   ");
    all_characters_are_the_same("2");
    all_characters_are_the_same("333");
    all_characters_are_the_same(".55");
    all_characters_are_the_same("tttTTT");
    all_characters_are_the_same("4444 444k");
    return 0;
}
Output:
input: "", length: 0
All characters are the same.

input: "   ", length: 3
All characters are the same.

input: "2", length: 1
All characters are the same.

input: "333", length: 3
All characters are the same.

input: ".55", length: 3
Not all characters are the same.
Character '5' (hex 35) at position 2 is not the same as '.'.

input: "tttTTT", length: 6
Not all characters are the same.
Character 'T' (hex 54) at position 4 is not the same as 't'.

input: "4444 444k", length: 9
Not all characters are the same.
Character ' ' (hex 20) at position 5 is not the same as '4'.

Clojure

(defn check-all-chars-same [s]
  (println (format "String (%s) of len: %d" s (count s)))
  (let [num-same (-> (take-while #(= (first s) %) s)
                     count)]
    (if (= num-same (count s))
      (println "...all characters the same")
      (println (format "...character %d differs - it is 0x%x"
                       num-same
                       (byte (nth s num-same)))))))

  (map check-all-chars-same
         [""
          "   "
          "2"
          "333"
          ".55"
          "tttTTT"
          "4444 444k"])
Output:
(String () of len: 0
...all characters the same
String (   ) of len: 3
...all characters the same
String (2) of len: 1
...all characters the same
String (333) of len: 3
...all characters the same
String (.55) of len: 3
...character 1 differs - it is 0x35
String (tttTTT) of len: 6
...character 3 differs - it is 0x54
String (4444 444k) of len: 9
...character 4 differs - it is 0x20

Common Lisp

Usage : (strequ string(s)) or (strequ) for auto-test

(defun strequ (&rest str)
    (if (not str) (setf str (list "" "   " "2" "333" ".55" "tttTTT" "4444 444k")))
    (dolist (s str)
        (do ((i 0 (1+ i)))
            ((cond
                ((= i (length s))
                    (format t "\"~a\" [~d] : All characters are identical.~%" s (length s)) t)
                ((char/= (char s i) (char s 0))
                    (format t "\"~a\" [~d] : '~c' (0x~0x) at index ~d is different.~%" s (length s) (char s i) (char-int (char s i)) i) t))))))
Output:
"" [0] : All characters are identical.
"   " [3] : All characters are identical.
"2" [1] : All characters are identical.
"333" [3] : All characters are identical.
".55" [3] : '5' (0x35) at index 1 is different.
"tttTTT" [6] : 'T' (0x54) at index 3 is different.
"4444 444k" [9] : ' ' (0x20) at index 4 is different.

D

Translation of: Kotlin
import std.stdio;

void analyze(string s) {
    writefln("Examining [%s] which has a length of %d:", s, s.length);
    if (s.length > 1) {
        auto b = s[0];
        foreach (i, c; s[1..$]) {
            if (c != b) {
                writeln("    Not all characters in the string are the same.");
                writefln("    '%c' (0x%x) is different at position %d", c, c, i);
                return;
            }
        }
    }
    writeln("    All characters in the string are the same.");
}

void main() {
    auto strs = ["", "   ", "2", "333", ".55", "tttTTT", "4444 444k"];
    foreach (str; strs) {
        analyze(str);
    }
}
Output:
Examining [] which has a length of 0:
    All characters in the string are the same.
Examining [   ] which has a length of 3:
    All characters in the string are the same.
Examining [2] which has a length of 1:
    All characters in the string are the same.
Examining [333] which has a length of 3:
    All characters in the string are the same.
Examining [.55] which has a length of 3:
    Not all characters in the string are the same.
    '5' (0x35) is different at position 0
Examining [tttTTT] which has a length of 6:
    Not all characters in the string are the same.
    'T' (0x54) is different at position 2
Examining [4444 444k] which has a length of 9:
    Not all characters in the string are the same.
    ' ' (0x20) is different at position 3

Delphi

Translation of: D
program Determine_if_a_string_has_all_the_same_characters;

{$APPTYPE CONSOLE}

uses
  System.SysUtils;

procedure Analyze(s: string);
var
  b, c: char;
  i: Integer;
begin
  writeln(format('Examining [%s] which has a length of %d:', [s, s.Length]));
  if s.Length > 1 then
  begin
    b := s[1];
    for i := 2 to s.Length - 1 do
    begin
      c := s[i];
      if c <> b then
      begin
        writeln('    Not all characters in the string are the same.');
        writeln(format('    "%s" 0x%x is different at position %d', [c, Ord(c), i]));
        Exit;
      end;
    end;
  end;
  writeln('    All characters in the string are the same.');
end;

var
  TestCases: array of string = ['', '   ', '2', '333', '.55', 'tttTTT', '4444 444k'];
  w: string;

begin
  for w in TestCases do
    Analyze(w);
  Readln;
end.
Output:
Examining [] which has a length of 0:
    All characters in the string are the same.
Examining [   ] which has a length of 3:
    All characters in the string are the same.
Examining [2] which has a length of 1:
    All characters in the string are the same.
Examining [333] which has a length of 3:
    All characters in the string are the same.
Examining [.55] which has a length of 3:
    Not all characters in the string are the same.
    "5" 0x35 is different at position 2
Examining [tttTTT] which has a length of 6:
    Not all characters in the string are the same.
    "T" 0x54 is different at position 4
Examining [4444 444k] which has a length of 9:
    Not all characters in the string are the same.
    " " 0x20 is different at position 5

DuckDB

Works with: DuckDB version V1.1
Works with: DuckDB version V1.0

The algorithm presented here is somewhat inefficient due to currently inherent limitations of DuckDB.

Note also that despite its name, DuckDB's ascii() function returns the codepoint of the first character of its string argument.

create or replace function length_first_run_list(list) as (
  case when list = [] then 0
  else coalesce(list_position( list_transform(list, x -> (x=list[1])), false) - 1, length(list))
  end
 );

create or replace function first_run_length(string) as (
  select length_first_run_list(regexp_extract_all(string, '.'))
 );

# Sample data
create or replace table strings as VALUES
          (''),
       ('   '),
         ('2'),
       ('333'),
       ('.55'),
    ('tttTTT'),
 ('4444 444k'),
 ('🐶🐶🐺🐶'),
 ('🎄🎄🎄🎄');

# The task:
WITH cte as (
    SELECT string, first_run_length(string) as first_run
    FROM strings t(string)
  ),
  details as (
    SELECT *, (case when first_run != length(string) then first_run + 1 else NULL end) as "index"
    FROM cte
  )
  SELECT string,
         length(string) as length,
         first_run = length(string) as same,
         "index" as 'index of switch char',
         string["index"] as 'switch char',
         format('{:x}', ascii(string["index"])) as 'hex of switch char'
  FROM details;
Output:
┌───────────┬────────┬─────────┬──────────────────────┬─────────────┬────────────────────┐
│  string   │ length │  same   │ index of switch char │ switch char │ hex of switch char │
│  varchar  │ int64  │ boolean │        int64         │   varchar   │      varchar       │
├───────────┼────────┼─────────┼──────────────────────┼─────────────┼────────────────────┤
│           │      0 │ true    │                      │             │                    │
│           │      3 │ true    │                      │             │                    │
│ 2         │      1 │ true    │                      │             │                    │
│ 333       │      3 │ true    │                      │             │                    │
│ .55       │      3 │ false   │                    2 │ 5           │ 35                 │
│ tttTTT    │      6 │ false   │                    4 │ T           │ 54                 │
│ 4444 444k │      9 │ false   │                    5 │             │ 20                 │
│ 🐶🐶🐺🐶  │      4 │ false   │                    3 │ 🐺          │ 1f43a              │
│ 🎄🎄🎄🎄  │      4 │ true    │                      │             │                    │
└───────────┴────────┴─────────┴──────────────────────┴─────────────┴────────────────────┘

EasyLang

func$ hex h .
   for d in [ h div 16 h mod 16 ]
      if d > 9
         d += 7
      .
      h$ &= strchar (d + 48)
   .
   return h$
.
proc samechar s$ . .
   s$[] = strchars s$
   for i = 2 to len s$[]
      if s$[i] <> s$[i - 1]
         h = strcode s$[i]
         write " --> different: '" & s$[i] & "' (" & hex h & "h)"
         print "'  position: " & i
         return
      .
   .
   print " --> ok"
.
repeat
   s$ = input
   until s$ = "EOF"
   print "'" & s$ & "'" & " length " & len s$
   samechar s$
   print ""
.
input_data

   
2
333
.55
tttTTT
4444 444k
EOF

Ed

This example is incorrect. Please fix the code and remove this message.

Details: The task requires not only to output whether the characters are the same (or not), but also to:

* display what [1st] character is different

* display where the different character is in the string

* display the hexadecimal value of the different character

The current Ed example does none of those things, so is not a solution to the task.

Consider whether Ed can realistically be used to solve this task.

The current example is also specifically incorrect insofar as: 1. The empty string in the input file returns, "Not all characters are the same in ". (NB: The task specifies, "a zero-length (empty) string shall be considered as all the same character(s)"), and 2. The one-space line is shown as returning, "Not all characters are the same in ", but that is not what the code produces.

H
g/^(.)\1*$/s//All the characters are the same in &/
v/All the characters/s/.*/Not all characters are the same in &/
,p
Q
Output:
$ cat string-same.ed | ed -GlEs string-same.input 
Newline appended
Not all characters are the same in 
Not all characters are the same in 
All the characters are the same in 2
All the characters are the same in 333
Not all characters are the same in .55
Not all characters are the same in tttTTT
Not all characters are the same in 4444 444k

Erlang

-module(string_examples).
-export([examine_all_same/1, all_same_examples/0]).

all_same_characters([], _Offset) ->
    all_same;
all_same_characters([_], _Offset) ->
    all_same;
all_same_characters([X, X | Rest], Offset) ->
    all_same_characters([X | Rest], Offset + 1);
all_same_characters([X, Y | _Rest], Offset) when X =/= Y ->
    {not_all_same, Y, Offset + 1}.

examine_all_same(String) ->
    io:format("String \"~ts\" of length ~p:~n", [String, length(String)]),
    case all_same_characters(String, 0) of
        all_same ->
            io:format("  All characters are the same.~n~n");
        {not_all_same, OffendingChar, Offset} ->
            io:format("  Not all characters are the same.~n"),
            io:format("  Char '~tc' (0x~.16b) at offset ~p differs.~n~n",
                      [OffendingChar, OffendingChar, Offset])
    end.

all_same_examples() ->
    Strings = ["",
               "   ",
               "2",
               "333",
               ".55",
               "tttTTT",
               "4444 444k",
               "pépé",
               "🐶🐶🐺🐶",
               "🎄🎄🎄🎄"],
    lists:foreach(fun examine_all_same/1, Strings).
Output:
$ erl
Erlang/OTP 23 [erts-11.1.8] [source] [64-bit] [smp:12:12] [ds:12:12:10] [async-threads:1]

Eshell V11.1.8  (abort with ^G)
1> c(string_examples).
{ok,string_examples}
2> string_examples:all_same_examples().
String "" of length 0:
  All characters are the same.

String "   " of length 3:
  All characters are the same.

String "2" of length 1:
  All characters are the same.

String "333" of length 3:
  All characters are the same.

String ".55" of length 3:
  Not all characters are the same.
  Char '5' (0x35) at offset 1 differs.

String "tttTTT" of length 6:
  Not all characters are the same.
  Char 'T' (0x54) at offset 3 differs.

String "4444 444k" of length 9:
  Not all characters are the same.
  Char ' ' (0x20) at offset 4 differs.

String "pépé" of length 4:
  Not all characters are the same.
  Char 'é' (0xe9) at offset 1 differs.

String "🐶🐶🐺🐶" of length 4:
  Not all characters are the same.
  Char '🐺' (0x1f43a) at offset 2 differs.

String "🎄🎄🎄🎄" of length 4:
  All characters are the same.

ok

F#

// Determine if a string has all the same characters. Nigel Galloway: June 9th., 2020
let fN n=if String.length n=0 then None else n.ToCharArray()|>Array.tryFindIndex(fun g->g<>n.[0])

let allSame n=match fN n with
               Some g->printfn "First different character in <<<%s>>> (length %d) is hex %x at position %d" n n.Length (int n.[g]) g
              |_->printfn "All Characters are the same in <<<%s>>> (length %d)" n n.Length 


allSame ""
allSame "   "
allSame "2"
allSame "333"
allSame ".55"
allSame "tttTTT"
allSame "4444 444k"
Output:
All Characters are the same in <<<>>> (length 0)
All Characters are the same in <<<   >>> (length 3)
All Characters are the same in <<<2>>> (length 1)
All Characters are the same in <<<333>>> (length 3)
First different character in <<<.55>>> (length 3) is hex 35 at position 1
First different character in <<<tttTTT>>> (length 6) is hex 54 at position 3
First different character in <<<4444 444k>>> (length 9) is hex 20 at position 4

Factor

USING: formatting io kernel math.parser sequences ;

: find-diff ( str -- i elt ) dup ?first [ = not ] curry find ;
: len. ( str -- ) dup length "%u — length %d — " printf ;
: same. ( -- ) "contains all the same character." print ;
: diff. ( -- ) "contains a different character at " write ;

: not-same. ( i elt -- )
    dup >hex diff. "index %d: '%c' (0x%s)\n" printf ;

: sameness-report. ( str -- )
    dup len. find-diff dup [ not-same. ] [ 2drop same. ] if ;

{
    ""
    "   "
    "2"
    "333"
    ".55"
    "tttTTT"
    "4444 444k"
} [ sameness-report. ] each
Output:
"" — length 0 — contains all the same character.
"   " — length 3 — contains all the same character.
"2" — length 1 — contains all the same character.
"333" — length 3 — contains all the same character.
".55" — length 3 — contains a different character at index 1: '5' (0x35)
"tttTTT" — length 6 — contains a different character at index 3: 'T' (0x54)
"4444 444k" — length 9 — contains a different character at index 4: ' ' (0x20)

Forth

: samechars? ( str-addr str-len -- )
   [char] " emit 2dup type [char] " emit ."  length: " dup . ." -> "
   dup 1 > if
      over c@ swap 1 do
         over i + c@ over <> if
            ." different character '" drop i + c@ dup emit
            ." ' ($" hex 1 .r ." ) at " decimal i . cr unloop exit
         then
      loop
   then 2drop ." all characters are the same" cr ;

s" " samechars?
s"    " samechars?
s" 2" samechars?
s" 333" samechars?
s" .55" samechars?
s" tttTTT" samechars?
s" 4444 444k" samechars?
Output:
"" length: 0 -> all characters are the same
"   " length: 3 -> all characters are the same
"2" length: 1 -> all characters are the same
"333" length: 3 -> all characters are the same
".55" length: 3 -> different character '5' ($35) at 1 
"tttTTT" length: 6 -> different character 'T' ($54) at 3 
"4444 444k" length: 9 -> different character ' ' ($20) at 4 

Fortran

Basically, just a simple call to the intrinsic VERIFY() procedure. Could also have been done with an INDEX() call in this simple case where the set of characters to match is a single character. A fancier format statement would eliminate the need for the HEX() procedure.

program demo_verify
implicit none
    call homogeneous('')
    call homogeneous('2')
    call homogeneous('333')
    call homogeneous('.55')
    call homogeneous('tttTTT')
    call homogeneous('4444  444k')
contains

subroutine homogeneous(str)
character(len=*),intent(in)  :: str
character(len=:),allocatable :: ch
character(len=*),parameter   :: g='(*(g0))'
integer :: where
   if(len(str)>0)then;ch=str(1:1);else;ch='';endif
   where=verify(str,ch)
   if(where.eq.0)then
     write(*,g)'STR: "',str,'" LEN: ',len(str),'. All chars are a ','"'//ch//'"'
   else
     write(*,g)'STR: "',str,'" LEN: ',len(str), &
     & '. Multiple chars found. First difference at position ',where, &
     & ' where a ','"'//str(where:where)//'"(hex:',hex(str(where:where)),') was found.'
     write(*,g)repeat(' ',where+5),'^'
   endif
end subroutine homogeneous

function hex(ch) result(hexstr)
character(len=1),intent(in) :: ch
character(len=:),allocatable :: hexstr
   hexstr=repeat(' ',100)
   write(hexstr,'(Z0)')ch
   hexstr=trim(hexstr)
end function hex 

end program demo_verify
Output:
STR: "" LEN: 0. All chars are a ""
STR: "2" LEN: 1. All chars are a "2"
STR: "333" LEN: 3. All chars are a "3"
STR: ".55" LEN: 3. Multiple chars found. First difference at position 2 where a "5"(hex:35) was found.
       ^
STR: "tttTTT" LEN: 6. Multiple chars found. First difference at position 4 where a "T"(hex:54) was found.
         ^
STR: "4444  444k" LEN: 10. Multiple chars found. First difference at position 5 where a " "(hex:20) was found.
          ^

FreeBASIC

dim as string s, nxt

input "Enter string:  ", s

if len(s)<2 then   'A string with one or zero characters passes by default
    print "All characters are the same."
    end
end if

dim as ubyte i

for i = 1 to len(s)-1
    nxt = mid(s, i+1, 1)
    if mid(s, i, 1)<>nxt then   'if any character differs from the previous one
        print "First non-matching char is "+nxt
        print "It occurs at position "+str(i+1)
        print "Its hex value is "+hex(asc(nxt))
        end
    end if
next i

'otherwise, success!
print "All characters are the same."
Output:
Enter string:  
All characters are the same.

Enter string:     
All characters are the same.

Enter string:  2
All characters are the same.

Enter string:  333
All characters are the same.

Enter string:  .55
First non-matching char is 5
It occurs at position 2
Its hex value is 35

Enter string:  tttTTT
First non-matching char is T
It occurs at position 4
Its hex value is 54

Enter string:  4444 444k
First non-matching char is  
It occurs at position 5
Its hex value is 20

FutureBasic

FutureBasic's CFStrings are zero-based

defstr byte

void local fn CheckString( s as CFStringRef )
  print @"String: \"";s;@"\""
  
  long length = len(s)
  if ( length )
    unichar prevChr = ucc(s)
    for long i = 1 to length - 1
      unichar chr = ucc(s,i)
      if ( chr != prevChr )
        print ,@"character ";ucs(chr);@" at position ";i;@", 0x";hex(chr);@", is the first different character"
        return
      end if
      prevChr = chr
    next
  end if
  
  print ,@"all characters are the same"
end fn

fn CheckString( @"" )
fn CheckString( @"   " )
fn CheckString( @"2" )
fn CheckString( @"333" )
fn CheckString( @".55" )
fn CheckString( @"tttTTT" )
fn CheckString( @"4444 444k" )

HandleEvents
Output:
String: ""
  all characters are the same
String: "   "
  all characters are the same
String: "2"
  all characters are the same
String: "333"
  all characters are the same
String: ".55"
  character "5" at position 1, 0x35, is the first different character
String: "tttTTT"
  character "T" at position 3, 0x54, is the first different character
String: "4444 444k"
  character " " at position 4, 0x20, is the first different character

Go

package main

import "fmt"

func analyze(s string) {
    chars := []rune(s)
    le := len(chars)
    fmt.Printf("Analyzing %q which has a length of %d:\n", s, le)
    if le > 1 {
        for i := 1; i < le; i++ {
            if chars[i] != chars[i-1] {
                fmt.Println("  Not all characters in the string are the same.")
                fmt.Printf("  %q (%#[1]x) is different at position %d.\n\n", chars[i], i+1)
                return
            }
        }
    }
    fmt.Println("  All characters in the string are the same.\n")
}

func main() {
    strings := []string{
        "",
        "   ",
        "2",
        "333",
        ".55",
        "tttTTT",
        "4444 444k",
        "pépé",
        "🐶🐶🐺🐶",
        "🎄🎄🎄🎄",
    }
    for _, s := range strings {
        analyze(s)
    }
}
Output:
Analyzing "" which has a length of 0:
  All characters in the string are the same.

Analyzing "   " which has a length of 3:
  All characters in the string are the same.

Analyzing "2" which has a length of 1:
  All characters in the string are the same.

Analyzing "333" which has a length of 3:
  All characters in the string are the same.

Analyzing ".55" which has a length of 3:
  Not all characters in the string are the same.
  '5' (0x35) is different at position 2.

Analyzing "tttTTT" which has a length of 6:
  Not all characters in the string are the same.
  'T' (0x54) is different at position 4.

Analyzing "4444 444k" which has a length of 9:
  Not all characters in the string are the same.
  ' ' (0x20) is different at position 5.

Analyzing "pépé" which has a length of 4:
  Not all characters in the string are the same.
  'é' (0xe9) is different at position 2.

Analyzing "🐶🐶🐺🐶" which has a length of 4:
  Not all characters in the string are the same.
  '🐺' (0x1f43a) is different at position 3.

Analyzing "🎄🎄🎄🎄" which has a length of 4:
  All characters in the string are the same.

Groovy

Translation of: Java
class Main {
    static void main(String[] args) {
        String[] tests = ["", "   ", "2", "333", ".55", "tttTTT", "4444 444k"]
        for (String s : tests) {
            analyze(s)
        }
    }

    static void analyze(String s) {
        println("Examining [$s] which has a length of ${s.length()}")
        if (s.length() > 1) {
            char firstChar = s.charAt(0)
            int lastIndex = s.lastIndexOf(firstChar as String)
            if (lastIndex != 0) {
                println("\tNot all characters in the string are the same.")
                println("\t'$firstChar' (0x${Integer.toHexString(firstChar as Integer)}) is different at position $lastIndex")
                return
            }
        }
        println("\tAll characters in the string are the same.")
    }
}
Output:
Examining [] which has a length of 0
	All characters in the string are the same.
Examining [   ] which has a length of 3
	Not all characters in the string are the same.
	' ' (0x20) is different at position 2
Examining [2] which has a length of 1
	All characters in the string are the same.
Examining [333] which has a length of 3
	Not all characters in the string are the same.
	'3' (0x33) is different at position 2
Examining [.55] which has a length of 3
	All characters in the string are the same.
Examining [tttTTT] which has a length of 6
	Not all characters in the string are the same.
	't' (0x74) is different at position 2
Examining [4444 444k] which has a length of 9
	Not all characters in the string are the same.
	'4' (0x34) is different at position 7

Haskell

import Numeric (showHex)
import Data.List (span)
import Data.Char (ord)

inconsistentChar :: Eq a => [a] -> Maybe (Int, a)
inconsistentChar [] = Nothing
inconsistentChar xs@(x:_) =
  let (pre, post) = span (x ==) xs
  in if null post
       then Nothing
       else Just (length pre, head post)


---------------------------TEST----------------------------
samples :: [String]
samples = ["   ", "2", "333", ".55", "tttTTT", "4444 444"]

main :: IO ()
main = do
  let w = succ . maximum $ length <$> samples
      justifyRight n c = (drop . length) <*> (replicate n c ++)
      f = (++ "' -> ") . justifyRight w ' ' . ('\'' :)
  (putStrLn . unlines) $
    (\s ->
        maybe
          (f s ++ "consistent")
          (\(n, c) ->
              f s ++
              "inconsistent '" ++
              c : "' (0x" ++ showHex (ord c) ")" ++ " at char " ++ show (succ n))
          (inconsistentChar s)) <$>
    samples

and inconsistentChar could alternatively be defined in terms of findIndex:

import Data.List (findIndex)

inconsistentChar :: Eq a => [a] -> Maybe (Int, a)
inconsistentChar [] = Nothing
inconsistentChar xs@(x:_) = findIndex (x /=) xs >>= Just . ((,) <*> (xs !!))
Output:
     '   ' -> consistent
       '2' -> consistent
     '333' -> consistent
     '.55' -> inconsistent '5' (0x35) at char 2
  'tttTTT' -> inconsistent 'T' (0x54) at char 4
'4444 444' -> inconsistent ' ' (0x20) at char 5

Insitux

Translation of: Clojure

With a minor change from the Clojure entry - showing ^ underneath the first inconsistent character.

(function check-all-chars-same string
  (print "String (" string ") of len: " (len string))
  (let num-same (count-while (= (0 string)) string))
  (return-when (= num-same (len string))
    (print "...all characters the same"))
  (print (pad-left " " (+ 9 num-same) "^"))
  (print "...character " num-same " differs - it is 0x"
    (to-base 16 (char-code (num-same string)))))

(map check-all-chars-same ["" "   " "2" "333" ".55" "tttTTT" "4444 444k"])
Output:
String () of len: 0
...all characters the same
String (   ) of len: 3
...all characters the same
String (2) of len: 1
...all characters the same
String (333) of len: 3
...all characters the same
String (.55) of len: 3
         ^
...character 1 differs - it is 0x35
String (tttTTT) of len: 6
           ^
...character 3 differs - it is 0x54
String (4444 444k) of len: 9
            ^
...character 4 differs - it is 0x20

J

In J, #~.y gives a count of the unique items (characters) in y.

Here's a relatively concise (and grammatical) approach. For grammatical reasons we report the count of characters up through the differing character position, rather than its index:

require'convert'
task=: {{
  if. 1>:#t=. ~.y do.
    echo 'all ',(":#y),' character(s) same in "',y,'"'
  else.
    j=. ":1+y i. ch=.1{t
    echo '"',ch,'" (hex: ',(hfd 3 u:ch),', character ',j,' of ',(":#y),') differs from previous characters in "',y,'"'
  end.
}}

And here's the task examples with this approach:

   task@>'';'   ';'2';'333';'.55';'tttTTT';'4444 444k'
all 0 character(s) same in ""
all 3 character(s) same in "   "
all 1 character(s) same in "2"
all 3 character(s) same in "333"
"5" (hex: 35, character 2 of 3) differs from previous characters in ".55"
"T" (hex: 54, character 4 of 6) differs from previous characters in "tttTTT"
" " (hex: 20, character 5 of 9) differs from previous characters in "4444 444k"

Java

import java.util.regex.Matcher;
import java.util.regex.Pattern;
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;
}
'' 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


Alternate implementations

public class Main{
	public static void main(String[] args){
		String[] tests = {"", "   ", "2", "333", ".55", "tttTTT", "4444 444k"};
		for(String s:tests)
			analyze(s);
	}

	public static void analyze(String s){
		System.out.printf("Examining [%s] which has a length of %d:\n", s, s.length());
		if(s.length() > 1){
			char firstChar = s.charAt(0);
			int lastIndex = s.lastIndexOf(firstChar);
			if(lastIndex != 0){
				System.out.println("\tNot all characters in the string are the same.");
				System.out.printf("\t'%c' (0x%x) is different at position %d\n", firstChar, (int) firstChar, lastIndex);
				return;
			}
		}
		System.out.println("\tAll characters in the string are the same.");
	}
}
Output:
Examining [] which has a length of 0:
	All characters in the string are the same.
Examining [   ] which has a length of 3:
	Not all characters in the string are the same.
	' ' (0x20) is different at position 2
Examining [2] which has a length of 1:
	All characters in the string are the same.
Examining [333] which has a length of 3:
	Not all characters in the string are the same.
	'3' (0x33) is different at position 2
Examining [.55] which has a length of 3:
	All characters in the string are the same.
Examining [tttTTT] which has a length of 6:
	Not all characters in the string are the same.
	't' (0x74) is different at position 2
Examining [4444 444k] which has a length of 9:
	Not all characters in the string are the same.
	'4' (0x34) is different at position 7

Using Java 8

import java.util.OptionalInt;

public final class AllSameCharacters {

	public static void main(String[] aArgs) {
		String[] words = { "", "   ", "2", "333", ".55", "tttTTT", "4444 444k" };
		for ( String word : words ) {
			analyse(word);
		}		
	}
	
	private static void analyse(String aText) {
		System.out.println("Examining \"" + aText + "\", which has length " + aText.length() + ":");

		OptionalInt mismatch = aText.chars().filter( ch -> ch != aText.charAt(0) ).findFirst();		
		
		if ( mismatch.isPresent() ) {
			char fault = (char) mismatch.getAsInt();
			System.out.println("    Not all characters in the string are the same.");
			System.out.println("    Character \"" + fault + "\" (" + Integer.toHexString((char) fault)
			                        + ") is different at index " + aText.indexOf(fault));
		} else {
			System.out.println("    All characters in the string are the same.");			
		}		
	}

}
Output:
Examining "", which has length 0:
    All characters in the string are the same.
Examining "   ", which has length 3:
    All characters in the string are the same.
Examining "2", which has length 1:
    All characters in the string are the same.
Examining "333", which has length 3:
    All characters in the string are the same.
Examining ".55", which has length 3:
    Not all characters in the string are the same.
    Character "5" (35) is different at index 1
Examining "tttTTT", which has length 6:
    Not all characters in the string are the same.
    Character "T" (54) is different at index 3
Examining "4444 444k", which has length 9:
    Not all characters in the string are the same.
    Character " " (20) is different at index 4

JavaScript

const check = s => {
  const arr = [...s];
  const at = arr.findIndex(
      (v, i) => i === 0 ? false : v !== arr[i - 1]
  )
  const l = arr.length;
  const ok = at === -1;
  const p = ok ? "" : at + 1;
  const v = ok ? "" : arr[at];
  const vs = v === "" ? v : `"${v}"`
  const h = ok ? "" : `0x${v.codePointAt(0).toString(16)}`;
  console.log(`"${s}" => Length:${l}\tSame:${ok}\tPos:${p}\tChar:${vs}\tHex:${h}`)
}

['', '   ', '2', '333', '.55', 'tttTTT', '4444 444k', '🐶🐶🐺🐶', '🎄🎄🎄🎄'].forEach(check)
Output:

"" => Length:0 Same:true Pos: Char: Hex: " " => Length:3 Same:true Pos: Char: Hex: "2" => Length:1 Same:true Pos: Char: Hex: "333" => Length:3 Same:true Pos: Char: Hex: ".55" => Length:3 Same:false Pos:2 Char:"5" Hex:0x35 "tttTTT" => Length:6 Same:false Pos:4 Char:"T" Hex:0x54 "4444 444k" => Length:9 Same:false Pos:5 Char:" " Hex:0x20 "🐶🐶🐺🐶" => Length:4 Same:false Pos:3 Char:"🐺" Hex:0x1f43a "🎄🎄🎄🎄" => Length:4 Same:true Pos: Char: Hex:


Alternatively, emphasising the composition of generic and reusable (pure value returning) library functions, and remaining agnostic about console.log (which is not part of JavaScript itself – doesn't feature in the ECMAScript standard – and is not available in all JS contexts).

(() => {
    'use strict';
 
    // ---------- FIRST INCONSISTENT CHARACTER -----------
 
    // inconsistentChar :: String -> Maybe (Char, Int)
    const inconsistentChar = s =>
        // Just the first inconsistent character in a
        // string, paired with the index of its position,
        // or Nothing if all of the characters in a string 
        // are the same.
        2 > s.length ? (
            Nothing()
        ) : (() => {
            const [h, ...t] = s;
            const i = t.findIndex(c => h !== c);
            return -1 !== i ? (
                Just([t[i], 1 + i])
            ) : Nothing();
        })();
 
 
    // ---------------------- TEST -----------------------
    // main :: IO ()
    const main = () =>
        fTable(
            'First inconsistent character:\n'
        )(
            s => `${quoted("'")(s)} (${[...s].length} chars)`
        )(
            maybe('None')(pair => {
                const c = pair[0];
                return `${quoted("'")(c)} at index ` + (
                    `${pair[1]} (${showHex(ord(c))})`
                );
            })
        )(
            inconsistentChar
        )([
            '', '   ', '2', '333', '.55',
            'tttTTT', '4444 444k',
            '🐶🐶🐺🐶', '🎄🎄🎄🎄'
        ]);
 
 
    // ----------- REUSABLE GENERIC FUNCTIONS ------------
 
    // Just :: a -> Maybe a
    const Just = x => ({
        type: 'Maybe',
        Nothing: false,
        Just: x
    });
 
 
    // Nothing :: Maybe a
    const Nothing = () => ({
        type: 'Maybe',
        Nothing: true,
    });
 
 
    // fTable :: String -> (a -> String) -> 
    // (b -> String) -> (a -> b) -> [a] -> String
    const fTable = s =>
        // Heading -> x display function ->
        //           fx display function ->
        //    f -> values -> tabular string
        xShow => fxShow => f => xs => {
            const
                ys = xs.map(xShow),
                w = Math.max(...ys.map(length));
            return s + '\n' + zipWith(
                a => b => a.padStart(w, ' ') + ' -> ' + b
            )(ys)(
                xs.map(x => fxShow(f(x)))
            ).join('\n');
        };
 
 
    // maybe :: b -> (a -> b) -> Maybe a -> b
    const maybe = v =>
        // Default value (v) if m is Nothing, or f(m.Just)
        f => m => m.Nothing ? (
            v
        ) : f(m.Just);
 
 
    // showHex :: Int -> String
    const showHex = n =>
        // Hexadecimal string for a given integer.
        '0x' + n.toString(16);
 
 
    // length :: [a] -> Int
    const length = xs =>
        // Returns Infinity over objects without finite
        // length. This enables zip and zipWith to choose
        // the shorter argument when one is non-finite,
        // like cycle, repeat etc
        'GeneratorFunction' !== xs.constructor
        .constructor.name ? (
            xs.length
        ) : Infinity;
 
 
    // list :: StringOrArrayLike b => b -> [a]
    const list = xs =>
        // xs itself, if it is an Array,
        // or an Array derived from xs.
        Array.isArray(xs) ? (
            xs
        ) : Array.from(xs || []);
 
 
    // ord :: Char -> Int
    const ord = c =>
        // Unicode ordinal value of the character.
        c.codePointAt(0);
 
 
    // quoted :: Char -> String -> String
    const quoted = c =>
        // A string flanked on both sides
        // by a specified quote character.
        s => c + s + c;
 
 
    // take :: Int -> [a] -> [a]
    // take :: Int -> String -> String
    const take = n =>
        // The first n elements of a list,
        // string of characters, or stream.
        xs => 'GeneratorFunction' !== xs
        .constructor.constructor.name ? (
            xs.slice(0, n)
        ) : [].concat.apply([], Array.from({
            length: n
        }, () => {
            const x = xs.next();
            return x.done ? [] : [x.value];
        }));
 
 
    // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
    const zipWith = f =>
        // A map of f over each stepwise pair in 
        // xs and ys, up to the length of the shorter
        // of those lists.
        xs => ys => {
            const
                n = Math.min(length(xs), length(ys)),
                vs = take(n)(list(ys));
            return take(n)(list(xs))
                .map((x, i) => f(x)(vs[i]));
        };
 
    // MAIN ---
    return main()
})();
Output:
First inconsistent character:

         '' (0 chars) -> None
      '   ' (3 chars) -> None
        '2' (1 chars) -> None
      '333' (3 chars) -> None
      '.55' (3 chars) -> '5' at index 1 (0x35)
   'tttTTT' (6 chars) -> 'T' at index 3 (0x54)
'4444 444k' (9 chars) -> ' ' at index 4 (0x20)
 '🐶🐶🐺🐶' (4 chars) -> '🐺' at index 2 (0x1f43a)
 '🎄🎄🎄🎄' (4 chars) -> None

jq

jq's "index origin" is 0. The hexadecimal encodings can be computed using the jq code at Non-decimal_radices/Convert#jq.


jq -rn '

  def firstdifferent:
    label $out
    | foreach explode[] as $i ({index:-1};
        .prev = .i | .i = $i | .index +=1;
        if .prev and $i != .prev then .index, break $out else empty end)
      // null ;
  
  def lpad($n): " "*($n-length) + "\"\(.)\"" ;
  
  [" "*10, "length", "same", "index", "char"],
  (inputs
   | firstdifferent as $d
   | [lpad(10), length, ($d == null)] + (if $d then [$d, .[$d:$d+1]] else null end) )
  | @tsv
'
Output:

Using as input the (JSON) strings shown in the first column of the output as shown below, the output is:

          	length	same	index	char
          ""	0	true
       "   "	3	true
         "2"	1	true
       "333"	3	true
       ".55"	3	false	1	5
    "tttTTT"	6	false	3	T
 "4444 444k"	9	false	4	 
 "🐶🐶🐺🐶"	4	false	2	🐺
 "🎄🎄🎄🎄"	4	true

Julia

firstdifferent(s) = isempty(s) ? nothing : findfirst(x -> x != s[1], s)

function testfunction(strings)
   println("String                  | Length | All Same | First Different(Hex) | Position\n" *
           "-----------------------------------------------------------------------------")
    for s in strings
        n = firstdifferent(s)
        println(rpad(s, 27), rpad(length(s), 9), n == nothing ? "yes" :
            rpad("no               $(s[n])   ($(string(Int(s[n]), base=16)))", 36) * string(n))
    end
end

testfunction([
	"",
	"   ",
	"2",
	"333",
    ".55",
    "tttTTT",
    "4444 444k",
    "pépé",
    "🐶🐶🐺🐶",
    "🎄🎄🎄🎄",
])
Output:
String                  | Length | All Same | First Different(Hex) | Position
-----------------------------------------------------------------------------
                           0        yes
                           3        yes
2                          1        yes
333                        3        yes
.55                        3        no               5   (35)           2
tttTTT                     6        no               T   (54)           4
4444 444k                  9        no                   (20)           5
pépé                       4        no               é   (e9)           2
🐶🐶🐺🐶                 4        no               🐺  (1f43a)        9
🎄🎄🎄🎄                   4        yes

Kotlin

Translation of: Go
fun analyze(s: String) {
    println("Examining [$s] which has a length of ${s.length}:")
    if (s.length > 1) {
        val b = s[0]
        for ((i, c) in s.withIndex()) {
            if (c != b) {
                println("    Not all characters in the string are the same.")
                println("    '$c' (0x${Integer.toHexString(c.toInt())}) is different at position $i")
                return
            }
        }
    }
    println("    All characters in the string are the same.")
}

fun main() {
    val strs = listOf("", "   ", "2", "333", ".55", "tttTTT", "4444 444k")
    for (str in strs) {
        analyze(str)
    }
}
Output:
Examining [] which has a length of 0:
    All characters in the string are the same.
Examining [   ] which has a length of 3:
    All characters in the string are the same.
Examining [2] which has a length of 1:
    All characters in the string are the same.
Examining [333] which has a length of 3:
    All characters in the string are the same.
Examining [.55] which has a length of 3:
    Not all characters in the string are the same.
    '5' (0x35) is different at position 1
Examining [tttTTT] which has a length of 6:
    Not all characters in the string are the same.
    'T' (0x54) is different at position 3
Examining [4444 444k] which has a length of 9:
    Not all characters in the string are the same.
    ' ' (0x20) is different at position 4

Lambdatalk

{def firstDifferingChar 
 {def firstDifferingChar.r
  {lambda {:w :i :n}
   {if {or {> :i :n} {= {+ :i 1} {W.length :w}}}
   then all characters are the same
   else {if {not {W.equal? {W.get :i :w} {W.get {+ :i 1} :w}}}
   then at position {+ :i 1} {W.get :i :w} becomes {W.get {+ :i 1} :w} 
   else {firstDifferingChar.r :w {+ :i 1} :n}}}}}
 {lambda {:w}
  {if {= {W.length :w} 1}
   then :w is a single character
   else {firstDifferingChar.r :w 0 {W.length :w}}}}} 
-> firstDifferingChar 

{firstDifferingChar 2}
-> 2 is a single character
{firstDifferingChar 333}
-> all characters are the same
{firstDifferingChar .55}
-> at position 1 . becomes 5
{firstDifferingChar tttTTT}
-> at position 3 t becomes T

Lua

function analyze(s)
    print(string.format("Examining [%s] which has a length of %d:", s, string.len(s)))
    if string.len(s) > 1 then
        local last = string.byte(string.sub(s,1,1))
        for i=1,string.len(s) do
            local c = string.byte(string.sub(s,i,i))
            if last ~= c then
                print("    Not all characters in the string are the same.")
                print(string.format("    '%s' (0x%x) is different at position %d", string.sub(s,i,i), c, i - 1))
                return
            end
        end
    end
    print("    All characters in the string are the same.")
end

function main()
    analyze("")
    analyze("   ")
    analyze("2")
    analyze("333")
    analyze(".55")
    analyze("tttTTT")
    analyze("4444 444k")
end

main()
Output:
Examining [] which has a length of 0:
    All characters in the string are the same.
Examining [   ] which has a length of 3:
    All characters in the string are the same.
Examining [2] which has a length of 1:
    All characters in the string are the same.
Examining [333] which has a length of 3:
    All characters in the string are the same.
Examining [.55] which has a length of 3:
    Not all characters in the string are the same.
    '5' (0x35) is different at position 1
Examining [tttTTT] which has a length of 6:
    Not all characters in the string are the same.
    'T' (0x54) is different at position 3
Examining [4444 444k] which has a length of 9:
    Not all characters in the string are the same.
    ' ' (0x20) is different at position 4

Maple

CheckSame:=proc(s)
	local i, index;
	printf("input: \"%s\", length: %a\n", s, StringTools:-Length(s));
	for i from 2 to StringTools:-Length(s) do
		if (s[i - 1] <> s[i]) then
			printf("The given string has different characters.\n");
			printf("The first different character is %a (0x%x) which appears at index %a.\n\n", 
			 	  s[i], convert(s[i], 'bytes')[1], i);
			return;
		end if;
	end do;
	# if no difference found
	printf("The given string has all same characters.\n\n");
end proc:

# Test
CheckSame("");
CheckSame("   ");
CheckSame("2");
CheckSame("333");
CheckSame(".55");
CheckSame("tttTTT");
CheckSame("4444 444k");
Output:
input: "", length: 0
The given string has all same characters.

input: "   ", length: 3
The given string has all same characters.

input: "2", length: 1
The given string has all same characters.

input: "333", length: 3
The given string has all same characters.

input: ".55", length: 3
The given string has different characters.
The first different character is "5" (0x35) which appears at index 2.

input: "tttTTT", length: 6
The given string has different characters.
The first different character is "T" (0x54) which appears at index 4.

input: "4444 444k", length: 9
The given string has different characters.
The first different character is " " (0x20) which appears at index 5.

Mathematica / Wolfram Language

ClearAll[AllSameCharacters]
AllSameCharacters[s_String] := Module[{c = Characters[s], i = 0, tf},
  If[Length[c] > 1,
    tf = AllTrue[Rest[c], (i++; # == First[c]) &];
    If[tf,
     Print["input = \"", s, "\", Length = ", StringLength[s], 
      ", All the same!"]
     ,
     Print["input = \"", s, "\", Length = ", StringLength[s], 
      ", Character " <> ToString[i + 1] <> 
       " is different from character " <> ToString[i], ", hex = ", 
      IntegerString[First@ToCharacterCode[c[[i + 1]]], 16]]
     ]
    ,
    Print["input = \"", s, "\", Length = ", StringLength[s], 
     ", All the same!"]
    ];
  ]
AllSameCharacters[""]
AllSameCharacters["   "]
AllSameCharacters["2"]
AllSameCharacters["333"]
AllSameCharacters[".55"]
AllSameCharacters["tttTTT"]
AllSameCharacters["4444 444k"]
Output:
input = "", Length = 0, All the same!
input = "   ", Length = 3, All the same!
input = "2", Length = 1, All the same!
input = "333", Length = 3, All the same!
input = ".55", Length = 3, Character 2 is different from character 1, hex = 35
input = "tttTTT", Length = 6, Character 4 is different from character 3, hex = 54
input = "4444 444k", Length = 9, Character 5 is different from character 4, hex = 20

Nanoquery

Translation of: Java
def analyze(s)
    s = str(s)
    println "Examining [" + s + "] which has a length of " + str(len(s)) + ":"

    if len(s) < 2
        println "\tAll characters in the string are the same."
        return
    end

    for i in range(0, len(s) - 2)
        if s[i] != s[i + 1]
            println "\tNot all characters in the string are the same."
            println "\t'" + s[i + 1] + "' " + format("(0x%x)", ord(s[i + 1])) +\
                    " is different at position " + str(i + 2)
            return
        end
    end

    println "\tAll characters in the string are the same."
end

tests = {"", "   ", "2", "333", ".55", "tttTTT", "444 444k"}
for s in tests
   analyze(s)
end
Output:
Examining [] which has a length of 0:
        All characters in the string are the same.
Examining [   ] which has a length of 3:
        All characters in the string are the same.
Examining [2] which has a length of 1:
        All characters in the string are the same.
Examining [333] which has a length of 3:
        All characters in the string are the same.
Examining [.55] which has a length of 3:
        Not all characters in the string are the same.
        '5' (0x35) is different at position 2
Examining [tttTTT] which has a length of 6:
        Not all characters in the string are the same.
        'T' (0x54) is different at position 4
Examining [444 444k] which has a length of 8:
        Not all characters in the string are the same.
        ' ' (0x20) is different at position 4

Nim

import strformat

proc analyze(str: string) =
    if str.len() > 1:
        var first = str[0]
        for i, c in str:
            if c != first:
                echo "'", str, "': [len: ", str.len(), "] not all characters are the same. starts to differ at index ",
                    i, ": '", first, "' != '", c, "' [", fmt"{ord(c):#x}", "]"
                return
    echo "'", str, "': [len: ", str.len(), "] all characters are the same"

var strings = @["", "   ", "2", "333", ".55", "tttTTT", "4444 444k"]
for str in strings:
    analyze(str)
Output:
'': [len: 0] all characters are the same
'   ': [len: 3] all characters are the same
'2': [len: 1] all characters are the same
'333': [len: 3] all characters are the same
'.55': [len: 3] not all characters are the same. starts to differ at index 1: '.' != '5' [0x35]
'tttTTT': [len: 6] not all characters are the same. starts to differ at index 3: 't' != 'T' [0x54]
'4444 444k': [len: 9] not all characters are the same. starts to differ at index 4: '4' != ' ' [0x20]


OCaml

Original version by User:Vanyamil

(*  Task: Determine if a string has all the same characters *)

(*  Create a function that determines whether all characters in a string are identical,
    or returns the index of first different character.

    Using the option type here to combine the functionality.
*)
let str_first_diff_char (s : string) : int option = 
    let len = String.length s in
    if len = 0 
    then None
    else
    let first = s.[0] in
    let rec helper idx =
        if idx >= len 
        then None
        else if s.[idx] = first
        then helper (idx + 1)
        else Some idx
    in
    helper 1
;;

(*  Task display: using format of Ada 
    Example: 

Input = "333", length = 3
 All characters are the same.
Input = ".55", length = 3
 First difference at position 2, character = '5', hex = 16#35#
*)

let format_answer s = 
    let first_line = "Input = \"" ^ s ^ "\", length = " ^ (s |> String.length |> string_of_int) in
    let second_line = match str_first_diff_char s with
        | None -> " All characters are the same."
        | Some idx -> Printf.sprintf " First difference at position %d, character = %C, hex = %#x" (idx+1) s.[idx] (Char.code s.[idx])
    in
    print_endline first_line; print_endline second_line
;;

let _ = 
    [""; "   "; "2"; "333"; ".55"; "tttTTT"; "4444 444k"]
    |> List.iter format_answer
;;
Output:
Input = "", length = 0
 All characters are the same.
Input = "   ", length = 3
 All characters are the same.
Input = "2", length = 1
 All characters are the same.
Input = "333", length = 3
 All characters are the same.
Input = ".55", length = 3
 First difference at position 2, character = '5', hex = 0x35
Input = "tttTTT", length = 6
 First difference at position 4, character = 'T', hex = 0x54
Input = "4444 444k", length = 9
 First difference at position 5, character = ' ', hex = 0x20

OmniMark

This takes it a bit further, including characters other than ASCII.

; Command line: omnimark -sb determine.xom -of determine.txt
include "utf8pat.xin"
process
  local stream s variable initial {'', '   ', '2', '333', '.55', 'tttTTT', '4444 444k', '😁😁🙂😁😁'}
  repeat over s
    local stream last initial {''}
    local switch same initial {true}
    local stream poschar
    local integer poshex
    local integer poshex2
    local integer position initial {1}
    local integer len initial {0}
    repeat scan s
      match (["%0#" to "%127#"] | utf8-char) => char
        do when last = ''
          set last to char
        else when last != char
          do when same
            set poschar to char when same
            do when char matches utf8-char
              set poshex to utf8-char-number char
            else
              set poshex to char binary 0
            done
            deactivate same
          done
        done
        increment position when same
        increment len
    again
    output 'String "%g(s)" is %d(len) character'
    output 's' unless len = 1
    output ':%n'
    do when same
      output ' - All characters are the same.%n'
    else
      output ' - Not all characters are the same (position %d(position): "%g(poschar)" [hex=%16rud(poshex)])%n'
    done
  again
Output:
String "" is 0 characters:
 - All characters are the same.
String "   " is 3 characters:
 - All characters are the same.
String "2" is 1 character:
 - All characters are the same.
String "333" is 3 characters:
 - All characters are the same.
String ".55" is 3 characters:
 - Not all characters are the same (position 2: "5" [hex=35])
String "tttTTT" is 6 characters:
 - Not all characters are the same (position 4: "T" [hex=54])
String "4444 444k" is 9 characters:
 - Not all characters are the same (position 5: " " [hex=20])
String "😁😁🙂😁😁" is 5 characters:
 - Not all characters are the same (position 3: "🙂" [hex=1F642])

Pascal

program SameNessOfChar;
{$IFDEF FPC}
   {$MODE DELPHI}{$OPTIMIZATION ON,ALL}{$CODEALIGN proc=16}{$ALIGN 16}
{$ELSE}
  {$APPTYPE CONSOLE}
{$ENDIF}
uses
  sysutils;//Format 
const
  TestData : array[0..6] of String =
     ('','   ','2','333','.55','tttTTT','4444 444k');
function PosOfDifferentChar(const s: String):NativeInt;
var
  i: Nativeint;
  ch:char;
Begin
  result := length(s);
  IF result < 2 then
    EXIT;
  ch := s[1];
  i := 2;
  while (i< result) AND (S[i] =ch) do
    inc(i);
  result := i;
end;

procedure OutIsAllSame(const s: String);
var
  l,len: NativeInt;
Begin
  l := PosOfDifferentChar(s);
  len := Length(s);
  write('"',s,'" of length ',len);
  IF l = len then
    writeln(' contains all the same character')
  else
    writeln(Format(' is different at position %d "%s" (0x%X)',[l,s[l],Ord(s[l])]));
end;

var
  i : NativeInt;
begin
  For i := Low(TestData) to HIgh(TestData) do
    OutIsAllSame(TestData[i]);
end.
Output:
"" of length 0 contains all the same character
"   " of length 3 contains all the same character
"2" of length 1 contains all the same character
"333" of length 3 contains all the same character
".55" of length 3 is different at position 2 "5" (0x35)
"tttTTT" of length 6 is different at position 4 "T" (0x54)
"4444 444k" of length 9 is different at position 5 " " (0x20)

PascalABC.NET

procedure Analyze(s: String);
begin
  writeln('Examining ''', s, ''' which has a length of ', s.Length);
  if s.Length > 1 Then 
    foreach var c in s index i do 
      if c <> s[1] Then 
      begin
        WriteLn('    Not all characters in the string are the same.');
        WriteLn('    ''', c, ''' (0x', ord(c).tostring('x'), ')', ' is different at position ', i + 1);
        exit;
      end;
  WriteLn('    All characters in the string are the same.')
end;

begin
  var strs := |'', '    ', '2', '333', '.55', 'tttTTT', '4444 444k'|;
  foreach var s In strs do
    Analyze(s);
end.
Output:
Examining '' which has a length of 0
    All characters in the string are the same.
Examining '    ' which has a length of 4
    All characters in the string are the same.
Examining '2' which has a length of 1
    All characters in the string are the same.
Examining '333' which has a length of 3
    All characters in the string are the same.
Examining '.55' which has a length of 3
    Not all characters in the string are the same.
    '5' (0x35) is different at position 2
Examining 'tttTTT' which has a length of 6
    Not all characters in the string are the same.
    'T' (0x54) is different at position 4
Examining '4444 444k' which has a length of 9
    Not all characters in the string are the same.
    ' ' (0x20) is different at position 5

Perl

use strict;
use warnings;
use feature 'say';
use utf8;
binmode(STDOUT, ':utf8');
use List::AllUtils qw(uniq);
use Unicode::UCD 'charinfo';
use Unicode::Normalize qw(NFC);

for my $str (
    '',
    '   ',
    '2',
    '333',
    '.55',
    'tttTTT',
    '4444 444k',
    'Δ👍👨',
    '🇬🇧🇬🇧🇬🇧🇬🇧',
    "\N{LATIN CAPITAL LETTER A}\N{COMBINING DIAERESIS}\N{COMBINING MACRON}" .
    "\N{LATIN CAPITAL LETTER A WITH DIAERESIS}\N{COMBINING MACRON}" .
    "\N{LATIN CAPITAL LETTER A WITH DIAERESIS AND MACRON}"
) {
    my @S;
    push @S, NFC $1 while $str =~ /(\X)/g;
    printf qq{\n"$str" (length: %d) has }, scalar @S;
    my @U = uniq @S;
    if (1 != @U and @U > 0) {
        say 'different characters:';
        for my $l (@U) {
            printf "'%s' %s (0x%x) in positions: %s\n",
                $l, charinfo(ord $l)->{'name'}, ord($l), join ', ', map { 1+$_ } grep { $l eq $S[$_] } 0..$#S;
        }
    } else {
        say 'the same character in all positions.'
    }
}
Output:
"" (length: 0) has the same character in all positions.

"   " (length: 3) has the same character in all positions.

"2" (length: 1) has the same character in all positions.

"333" (length: 3) has the same character in all positions.

".55" (length: 3) has different characters:
'.' FULL STOP (0x2e) in positions: 1
'5' DIGIT FIVE (0x35) in positions: 2, 3

"tttTTT" (length: 6) has different characters:
't' LATIN SMALL LETTER T (0x74) in positions: 1, 2, 3
'T' LATIN CAPITAL LETTER T (0x54) in positions: 4, 5, 6

"4444 444k" (length: 9) has different characters:
'4' DIGIT FOUR (0x34) in positions: 1, 2, 3, 4, 6, 7, 8
' ' SPACE (0x20) in positions: 5
'k' LATIN SMALL LETTER K (0x6b) in positions: 9

"Δ👍👨" (length: 3) has different characters:
'Δ' GREEK CAPITAL LETTER DELTA (0x394) in positions: 1
'👍' THUMBS UP SIGN (0x1f44d) in positions: 2
'👨' MAN (0x1f468) in positions: 3

"🇬🇧🇬🇧🇬🇧🇬🇧" (length: 4) has the same character in all positions.

"ǞǞǞ" (length: 3) has the same character in all positions.

Phix

with javascript_semantics
procedure samechar(sequence s)
    string msg = "all characters are the same"
    integer l = length(s)
    if l>=2 then
        integer ch = s[1]
        for i=2 to l do
            integer si = s[i]
            if si!=ch then
                string su = utf32_to_utf8({si})
                msg = sprintf(`first different character "%s"(#%02x) at position %d`,{su,si,i})
                exit
            end if
        end for
    end if
    printf(1,"\"%s\" (length %d): %s\n",{utf32_to_utf8(s),l,msg})
end procedure
 
constant tests = {"","   ","2","333",".55","tttTTT","4444 444k",
                  utf8_to_utf32("🐶🐶🐺🐶"),utf8_to_utf32("🎄🎄🎄🎄")}
for i=1 to length(tests) do samechar(tests[i]) end for
Output:
"" (length 0): all characters are the same
"   " (length 3): all characters are the same
"2" (length 1): all characters are the same
"333" (length 3): all characters are the same
".55" (length 3): first different character "5"(#35) at position 2
"tttTTT" (length 6): first different character "T"(#54) at position 4
"4444 444k" (length 9): first different character " "(#20) at position 5
"🐶🐶🐺🐶" (length 4): first different character "🐺"(#1F43A) at position 3
"🎄🎄🎄🎄" (length 4): all characters are the same

As usual, the last two lines don't come out very nice on a Windows console.

PicoLisp

(de equal? (Str)
   (let (Lst (chop Str)  C (car Lst)  P 2  F)
      (prin Str ": ")
      (for A (cdr Lst)
         (NIL (= A C) (on F) (prin "First different character " A))
         (inc 'P) )
      (if F (prinl " at position: " P) (prinl "all characters are the same")) ) )
(equal?)
(equal? "   ")
(equal? "333")
(equal? ".55")
(equal? "tttTTT")
Output:
: all characters are the same
   : all characters are the same
333: all characters are the same
.55: First different character 5 at position: 2
tttTTT: First different character T at position: 4

Plain English

To run:
Start up.
Show the uniformity of "".
Show the uniformity of "   ".
Show the uniformity of "2".
Show the uniformity of "333".
Show the uniformity of ".55".
Show the uniformity of "tttTTT".
Show the uniformity of "4444 444k".
Wait for the escape key.
Shut down.

To find the first different character in a string giving a byte and a count:
If the string is blank, put -1 into the count; exit.
Put the string's first's target into a first letter.
Slap a substring on the string.
Loop.
If a counter is past the string's length, put -1 into the count; exit.
Put the substring's first's target into a letter.
If the letter is not the first letter, put the letter into the byte; put the counter minus 1 into the count; exit.
Add 1 to the substring's first.
Repeat.

To show the uniformity of a string:
Write """" then the string then """ (length " then the string's length then ") " on the console without advancing.
Find the first different character in the string giving a byte and a count.
If the count is -1, write "contains all the same character." on the console; exit.
Convert the byte to a nibble string.
Write "contains a different character at index " then the count then ": '" then the byte then "' (0x" then the nibble string then ")." on the console.
Output:
"" (length 0) contains all the same character.
"   " (length 3) contains all the same character.
"2" (length 1) contains all the same character.
"333" (length 3) contains all the same character.
".55" (length 3) contains a different character at index 1: '5' (0x35).
"tttTTT" (length 6) contains a different character at index 3: 'T' (0x54).
"4444 444k" (length 9) contains a different character at index 4: ' ' (0x20).

Prolog

Works with: SWI-Prolog version 7
:- system:set_prolog_flag(double_quotes,chars) .

main
:-
same_or_different("") ,
same_or_different("   ") ,
same_or_different("2") ,
same_or_different("333") ,
same_or_different(".55") ,
same_or_different("tttTTT") ,
same_or_different("4444 444k")
.

%!  same_or_different(INPUTz0)

same_or_different(INPUTz0)
:-
system:format('input string is "~s" .~n',[INPUTz0]) ,
examine(INPUTz0)
.

%!  examine(INPUTz0)

examine([])
:-
! ,
system:format('all the same characters .~n',[])
.

examine([COMPARE0|INPUTz0])
:-
examine(INPUTz0,COMPARE0,2,_INDEX_)
.

%!  examine(INPUTz0,COMPARE0,INDEX0,INDEX)

examine([],_COMPARE0_,INDEX0,INDEX0)
:-
! ,
system:format('all the same characters .~n',[])
.

examine([COMPARE0|INPUTz0],COMPARE0,INDEX0,INDEX)
:-
! ,
INDEX1 is INDEX0 + 1 ,
examine(INPUTz0,COMPARE0,INDEX1,INDEX)
.

examine([DIFFERENT0|_INPUTz0_],COMPARE0,INDEX0,INDEX0)
:-
prolog:char_code(DIFFERENT0,DIFFERENT_CODE) ,
system:format('character "~s" (hex ~16r) different than "~s" at 1-based index ~10r .~n',[[DIFFERENT0],DIFFERENT_CODE,[COMPARE0],INDEX0])
.
Output:
/*
?- main .
input string is "" .
all the same characters .
input string is "   " .
all the same characters .
input string is "2" .
all the same characters .
input string is "333" .
all the same characters .
input string is ".55" .
character "5" (hex 35) different than "." at 1-based index 2 .
input string is "tttTTT" .
character "T" (hex 54) different than "t" at 1-based index 4 .
input string is "4444 444k" .
character " " (hex 20) different than "4" at 1-based index 5 .
true.

?- 
*/

Python

Functional

What we are testing here is the cardinality of the set of characters from which a string is drawn, so the first thought might well be to use set.

On the other hand, itertools.groupby has the advantage of yielding richer information (the list of groups is ordered), for less work.

Works with: Python version 3.7
'''Determine if a string has all the same characters'''

from itertools import groupby


# firstDifferingCharLR :: String -> Either String Dict
def firstDifferingCharLR(s):
    '''Either a message reporting that no character changes were
       seen, or a dictionary with details of the  first character
       (if any) that differs from that at the head of the string.
    '''
    def details(xs):
        c = xs[1][0]
        return {
            'char': repr(c),
            'hex': hex(ord(c)),
            'index': s.index(c),
            'total': len(s)
        }
    xs = list(groupby(s))
    return Right(details(xs)) if 1 < len(xs) else (
        Left('Total length ' + str(len(s)) + ' - No character changes.')
    )


# TEST ----------------------------------------------------
# main :: IO ()
def main():
    '''Test of 7 strings'''

    print(fTable('First, if any, points of difference:\n')(repr)(
        either(identity)(
            lambda dct: dct['char'] + ' (' + dct['hex'] +
            ') at character ' + str(1 + dct['index']) +
            ' of ' + str(dct['total']) + '.'
        )
    )(firstDifferingCharLR)([
        '',
        '   ',
        '2',
        '333',
        '.55',
        'tttTTT',
        '4444 444'
    ]))


# GENERIC -------------------------------------------------

# either :: (a -> c) -> (b -> c) -> Either a b -> c
def either(fl):
    '''The application of fl to e if e is a Left value,
       or the application of fr to e if e is a Right value.
    '''
    return lambda fr: lambda e: fl(e['Left']) if (
        None is e['Right']
    ) else fr(e['Right'])


# identity :: a -> a
def identity(x):
    '''The identity function.'''
    return x


# fTable :: String -> (a -> String) ->
# (b -> String) -> (a -> b) -> [a] -> String
def fTable(s):
    '''Heading -> x display function -> fx display function ->
       f -> xs -> tabular string.
    '''
    def go(xShow, fxShow, f, xs):
        ys = [xShow(x) for x in xs]
        w = max(map(len, ys))
        return s + '\n' + '\n'.join(map(
            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),
            xs, ys
        ))
    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(
        xShow, fxShow, f, xs
    )


# Left :: a -> Either a b
def Left(x):
    '''Constructor for an empty Either (option type) value
       with an associated string.
    '''
    return {'type': 'Either', 'Right': None, 'Left': x}


# Right :: b -> Either a b
def Right(x):
    '''Constructor for a populated Either (option type) value'''
    return {'type': 'Either', 'Left': None, 'Right': x}


# MAIN ---
if __name__ == '__main__':
    main()
Output:
First, if any, points of difference:

        '' -> Total length 0 - No character changes.
     '   ' -> Total length 3 - No character changes.
       '2' -> Total length 1 - No character changes.
     '333' -> Total length 3 - No character changes.
     '.55' -> '5' (0x35) at character 2 of 3.
  'tttTTT' -> 'T' (0x54) at character 4 of 6.
'4444 444' -> ' ' (0x20) at character 5 of 8.


and for very long strings, itertools.takewhile (here used in the definition of a more general span function), should be slightly more efficient:

'''Determine if a string has all the same characters'''

from itertools import takewhile


# inconsistentChar :: String -> Maybe (Int, Char)
def inconsistentChar(s):
    '''Just the first inconsistent character and its position,
       or Nothing if all the characters of s are the same,
    '''
    if s:
        h = s[0]
        pre, post = span(lambda c: h == c)(s)
        return Just((len(pre), post[0])) if post else Nothing()
    else:
        return Nothing()


# --------------------------TEST---------------------------
# main :: IO ()
def main():
    '''Consistency tests of seven strings'''

    samples = ['', '   ', '2', '333', '.55', 'tttTTT', '4444 444']
    w = 1 + max(map(len, samples))

    def pfx(s):
        return ("'" + s).rjust(w) + "' -> "

    def charPosn(ic):
        i, c = ic
        return "inconsistent '" + c + "' (" + hex(ord(c)) + ")" + (
            " at char " + str(1 + i)
        )

    print(main.__doc__ + ':\n')
    print(
        '\n'.join([
            pfx(s) + maybe('consistent')(charPosn)(
                inconsistentChar(s)
            )
            for s in samples
        ])
    )


# -------------------------GENERIC-------------------------

# Just :: a -> Maybe a
def Just(x):
    '''Constructor for an inhabited Maybe (option type) value.
       Wrapper containing the result of a computation.
    '''
    return {'type': 'Maybe', 'Nothing': False, 'Just': x}


# Nothing :: Maybe a
def Nothing():
    '''Constructor for an empty Maybe (option type) value.
       Empty wrapper returned where a computation is not possible.
    '''
    return {'type': 'Maybe', 'Nothing': True}


# maybe :: b -> (a -> b) -> Maybe a -> b
def maybe(v):
    '''Either the default value v, if m is Nothing,
       or the application of f to x,
       where m is Just(x).
    '''
    return lambda f: lambda m: v if None is m or m.get('Nothing') else (
        f(m.get('Just'))
    )


# span :: (a -> Bool) -> [a] -> ([a], [a])
def span(p):
    '''The longest (possibly empty) prefix of xs
       that contains only elements satisfying p,
       tupled with the remainder of xs.
       span p xs is equivalent to (takeWhile p xs, dropWhile p xs).
    '''
    def go(xs):
        prefix = list(takewhile(p, xs))
        return (prefix, xs[len(prefix):])
    return lambda xs: go(xs)


# MAIN ---
if __name__ == '__main__':
    main()

Putting itertools aside, we could equivalently define inconsistentChar as:

# inconsistentChar :: String -> Maybe (Int, Char)
def inconsistentChar(s):
    '''Just the first inconsistent character and its index,
       or Nothing if all the characters of s are the same.
    '''
    return next(
        (Just(ix) for ix in enumerate(s) if s[0] != ix[1]),
        Nothing()
    )
Output:
Consistency tests of seven strings:

        '' -> consistent
     '   ' -> consistent
       '2' -> consistent
     '333' -> consistent
     '.55' -> inconsistent '5' (0x35) at char 2
  'tttTTT' -> inconsistent 'T' (0x54) at char 4
'4444 444' -> inconsistent ' ' (0x20) at char 5

Quackery

  [ 0 swap
    dup size 0 = iff 
      drop done 
    behead swap witheach
      [ over != if
          [ drop i^ 1+
            swap conclude ] ]
    drop ]                    is allsame ( [ --> n )

  ( 0 indicates all items are the same,
    otherwise n is first different item )

  [ say ' String: "' dup echo$
    say '" length ' dup size echo  
    dup allsame dup 0 = iff
      [ say ', all characters are the same.'
        2drop ]
    else
      [ say ', first difference is item '
        dup echo 
        say ', char "' 
        peek dup emit
        say '", hex: '
        16 base put echo base release
        say '.' ]
    cr ]                      is task    ( $ -->   )

  $ ""          task
  $ "   "       task
  $ "2"         task
  $ ".55"       task
  $ "tttTTT"    task
  $ "4444 444k" task
Output:
 String: "" length 0, all characters are the same.
 String: "   " length 3, all characters are the same.
 String: "2" length 1, all characters are the same.
 String: ".55" length 3, first difference is item 1, char "5", hex: 35.
 String: "tttTTT" length 6, first difference is item 3, char "T", hex: 54.
 String: "4444 444k" length 9, first difference is item 4, char " ", hex: 20.

R

isAllSame <- function(string)
{
  strLength <- nchar(string)
  if(length(strLength) > 1)
  {
    #R has a distinction between the length of a string and that of a character vector. It is a common source
    #of problems when coming from another language. We will try to avoid the topic here.
    #For our purposes, let us only say that there is a good reason why we have made
    #isAllSame(c("foo", "bar") immediately throw an error.
    stop("This task is intended for character vectors with lengths of at most 1.")
  }
  else if(length(strLength) == 0)
  {
    cat("Examining a character vector of length 0.\n")
    TRUE
  }
  else if(strLength == 0)
  {
    cat("Examining a character vector of length 1, containing an empty string.\n")
    TRUE
  }
  else
  {
    cat("Examining the string", paste0(sQuote(string), ","),
        "which is of length", paste0(strLength, ":"), "\n")
    #strsplit outputs a list. Its first element is the vector of characters that we desire.
    characters <- strsplit(string, "")[[1]]
    #Our use of match is using R's vector recycling rules. Every element is being checked
    #against the first.
    differentElementIndex <- match(FALSE, characters[1] == characters, nomatch = 0)
    if(differentElementIndex == 0)
    {
      cat("It has no duplicates.\n")
      TRUE
    }
    else
    {
      cat("It has duplicates. ")
      firstDifferentCharacter <- characters[differentElementIndex]
      cat(sQuote(firstDifferentCharacter), "is the first different character. It has hex value",
          sprintf("0x%X", as.integer(charToRaw(firstDifferentCharacter))),
          "and is at index", paste0(differentElementIndex, "."), "\n")
      FALSE
    }
  }
}

#Tests:
cat("Test: A string of length 0 (an empty string):\n")
cat("Test 1 of 2: An empty character vector:\n")
print(isAllSame(character(0)))
cat("Test 2 of 2: A character vector containing the empty string:\n")
print(isAllSame(""))
cat("Test: A string of length 3 which contains three blanks:\n")
print(isAllSame("   "))
cat("Test: A string of length 1 which contains 2:\n")
print(isAllSame("2"))
cat("Test: A string of length 3 which contains 333:\n")
print(isAllSame("333"))
cat("Test: A string of length 3 which contains .55:\n")
print(isAllSame(".55"))
cat("Test: A string of length 6 which contains tttTTT:\n")
print(isAllSame("tttTTT"))
cat("Test: A string of length 9 which contains 4444 444k:\n")
print(isAllSame("4444 444k"))
Output:
Test: A string of length 0 (an empty string):
Test 1 of 2: An empty character vector:
Examining a character vector of length 0.
[1] TRUE
Test 2 of 2: A character vector containing the empty string:
Examining a character vector of length 1, containing an empty string.
[1] TRUE
Test: A string of length 3 which contains three blanks:
Examining the string ‘   ’, which is of length 3: 
It has no duplicates.
[1] TRUE
Test: A string of length 1 which contains 2:
Examining the string ‘2’, which is of length 1: 
It has no duplicates.
[1] TRUE
Test: A string of length 3 which contains 333:
Examining the string ‘333’, which is of length 3: 
It has no duplicates.
[1] TRUE
Test: A string of length 3 which contains .55:
Examining the string ‘.55’, which is of length 3: 
It has duplicates. ‘5’ is the first different character. It has hex value 0x35 and is at index 2. 
[1] FALSE
Test: A string of length 6 which contains tttTTT:
Examining the string ‘tttTTT’, which is of length 6: 
It has duplicates. ‘T’ is the first different character. It has hex value 0x54 and is at index 4. 
[1] FALSE
Test: A string of length 9 which contains 4444 444k:
Examining the string ‘4444 444k’, which is of length 9: 
It has duplicates. ‘ ’ is the first different character. It has hex value 0x20 and is at index 5. 
[1] FALSE

Racket

#lang racket

(define (first-non-matching-index l =)
  (and (not (null? l)) (index-where l (curry (negate =) (car l)))))

(define (report-string-sameness s)
  (printf "~s (length: ~a): ~a~%"
          s
          (string-length s)
          (cond [(first-non-matching-index (string->list s) char=?)
                 => (λ (i)
                      (let ((c (string-ref s i)))
                        (format "first different character ~s(~a) at position: ~a" c (char->integer c) (add1 i))))]
                [else "all characters are the same"])))

(module+ test
  (for-each report-string-sameness '("" "   " "2" "333" ".55" "tttTTT" "4444 444k")))
Output:
"" (length: 0): all characters are the same
"   " (length: 3): all characters are the same
"2" (length: 1): all characters are the same
"333" (length: 3): all characters are the same
".55" (length: 3): first different character #\5(53) at position: 2
"tttTTT" (length: 6): first different character #\T(84) at position: 4
"4444 444k" (length: 9): first different character #\space(32) at position: 5

Raku

(formerly Perl 6)

Works with: Rakudo version 2020.08.1

The last string demonstrates how Raku can recognize that glyphs made up of different combinations of combining characters can compare the same. It is built up from explicit codepoints to show that each of the glyphs is made up of different combinations.

  -> $str {
    my $i = 0;
    print "\n{$str.raku} (length: {$str.chars}), has ";
    my %m;
    %m{$_}.push: ++$i for $str.comb;

    if %m > 1 {
        say "different characters:";
        say "'{.key}' ({.key.uninames}; hex ordinal: {(.key.ords).fmt: "0x%X"})" ~
        " in positions: {.value.join: ', '}" for %m.sort( *.value[0] );
    } else {
        say "the same character in all positions."
    }
} for
    '',
    '   ',
    '2',
    '333',
    '.55',
    'tttTTT',
    '4444 444k',
    '🇬🇧🇬🇧🇬🇧🇬🇧',
    "\c[LATIN CAPITAL LETTER A]\c[COMBINING DIAERESIS]\c[COMBINING MACRON]" ~
    "\c[LATIN CAPITAL LETTER A WITH DIAERESIS]\c[COMBINING MACRON]" ~
    "\c[LATIN CAPITAL LETTER A WITH DIAERESIS AND MACRON]",
    'AАΑꓮ𐌀𐊠Ꭺ'
Output:
"" (length: 0), has the same character in all positions.

"   " (length: 3), has the same character in all positions.

"2" (length: 1), has the same character in all positions.

"333" (length: 3), has the same character in all positions.

".55" (length: 3), has different characters:
'.' (FULL STOP; hex ordinal: 0x2E) in positions: 1
'5' (DIGIT FIVE; hex ordinal: 0x35) in positions: 2, 3

"tttTTT" (length: 6), has different characters:
't' (LATIN SMALL LETTER T; hex ordinal: 0x74) in positions: 1, 2, 3
'T' (LATIN CAPITAL LETTER T; hex ordinal: 0x54) in positions: 4, 5, 6

"4444 444k" (length: 9), has different characters:
'4' (DIGIT FOUR; hex ordinal: 0x34) in positions: 1, 2, 3, 4, 6, 7, 8
' ' (SPACE; hex ordinal: 0x20) in positions: 5
'k' (LATIN SMALL LETTER K; hex ordinal: 0x6B) in positions: 9

"🇬🇧🇬🇧🇬🇧🇬🇧" (length: 4), has the same character in all positions.

"ǞǞǞ" (length: 3), has the same character in all positions.

"AАΑꓮ𐌀𐊠Ꭺ" (length: 7), has different characters:
'A' (LATIN CAPITAL LETTER A; hex ordinal: 0x41) in positions: 1
'А' (CYRILLIC CAPITAL LETTER A; hex ordinal: 0x410) in positions: 2
'Α' (GREEK CAPITAL LETTER ALPHA; hex ordinal: 0x391) in positions: 3
'ꓮ' (LISU LETTER A; hex ordinal: 0xA4EE) in positions: 4
'𐌀' (OLD ITALIC LETTER A; hex ordinal: 0x10300) in positions: 5
'𐊠' (CARIAN LETTER A; hex ordinal: 0x102A0) in positions: 6
'Ꭺ' (CHEROKEE LETTER GO; hex ordinal: 0x13AA) in positions: 7

REXX

/*REXX program verifies that  all characters  in a string are all the same (character). */
@chr= '     [character'                               /* define a literal used for  SAY.*/
@all= 'all the same character for string (length'     /*    "   "    "     "    "    "  */
@.=                                              /*define a default for the  @.  array. */
parse arg x                                      /*obtain optional argument from the CL.*/
if x\=''  then       @.1= x                      /*if user specified an arg, use that.  */
          else do;   @.1=                        /*use this null string if no arg given.*/
                     @.2= '   '                  /* "    "          "    "  "  "    "   */
                     @.3= 2                      /* "    "          "    "  "  "    "   */
                     @.4= 333                    /* "    "          "    "  "  "    "   */
                     @.5= .55                    /* "    "          "    "  "  "    "   */
                     @.6= 'tttTTT'               /* "    "          "    "  "  "    "   */
                     @.7= 4444 444k              /* "    "          "    "  "  "    "   */
               end                               /* [↑]  seventh value contains a blank.*/

     do j=1;    L= length(@.j)                   /*obtain the length of an array element*/
     if j>1  &  L==0     then leave              /*if arg is null and  J>1, then leave. */
     r= allSame(@.j)                             /*R:  ≡0,  or the location of bad char.*/
     if r\==0  then ?= substr(@.j,r,1)           /*if  not  monolithic, obtain the char.*/
     if r==0   then say '   ' @all L"):"  @.j
               else say 'not' @all L"):"  @.j  @chr ?  "('"c2x(?)"'x)  at position"  r"]."
     end   /*j*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
allSame: procedure; parse arg y                  /*get a value from the argument list.  */
         if y==''  then return 0                 /*if  Y  is null,  then return 0 (zero)*/
         return verify(y, left(y,1) )            /*All chars the same?   Return 0 (zero)*/
                                                 /*                else  return location*/
output   when using the internal default inputs:
    all the same character for string (length 0):
    all the same character for string (length 3):
    all the same character for string (length 1): 2
    all the same character for string (length 3): 333
not all the same character for string (length 3): .55      [character 5 ('35'x)  at position 2].
not all the same character for string (length 6): tttTTT      [character T ('54'x)  at position 4].
not all the same character for string (length 9): 4444 444K      [character   ('20'x)  at position 5].

Ring

nputStr = ["","   ","2","333",".55","tttTTT","4444 444k"]

for word in inputStr
    for x = 1 to len(word)
        for y = x + 1 to len(word)
            if word[x] != word[y]
               char = word[y]
               ? "Input = " + "'" + word + "'" + ", length = " + len(word)
               ? " First difference at position " + y + ", character = " + "'" + char + "'"
               loop 3
            ok
        next
    next

    ? "Input = " + "'" + word + "'" + ", length = " + len(word)
    ? "  All characters are the same."
next
Output:
Input = '', length = 0
  All characters are the same.
Input = '   ', length = 3
  All characters are the same.
Input = '2', length = 1
  All characters are the same.
Input = '333', length = 3
  All characters are the same.
Input = '.55', length = 3
 First difference at position 2, character = '5'
Input = 'tttTTT', length = 6
 First difference at position 4, character = 'T'
Input = '4444 444k', length = 9
 First difference at position 5, character = ' '

RPL

Works with: Halcyon Calc version 4.2.7
≪ DUP SIZE → s n 
   ≪ "Examining [" s + "], length=" + n →STR + +
      1 CF 
      IF n THEN 
         s 1 1 SUB 1 
         DO 
            s OVER DUP SUB 
            IF 3 PICK OVER ≠ THEN 
               1 SF 
               ROT DROP SWAP 
            ELSE DROP 
            END 
         1 + 
         UNTIL DUP n ≥ 1 FS? OR END 
         DROP 
      ELSE DUP 
      END 
      IF 1 FC? THEN 
         DROP 
         "All chars are the same." 
      ELSE 
         "'" OVER + 
         "' (hex=" + OVER NUM HEX R→B →STR + 
         ") is different at pos " + s 4 ROLL POS →STR + 
      END 
   ≫
≫
'ALLSAME?' STO
≪ { "" "   " "2" "333" ".55" "tttTTT" "4444 444k" }
   → tl ≪ 
    1 tl SIZE FOR j
      tl j GET ALLSAME?
   NEXT
   ≫
≫
EVAL
Output:
14:"Examining [], length=0"
13:"All chars are the same"
12:"Examining [   ], length=3"
11:"All chars are the same"
10:"Examining [2], length=1"
9:"All chars are the same"
8:"Examining [333], length=3"
7:"All chars are the same"
6:"Examining [.55], length=3"
5:"'5' (hex=# 35h) is different at pos 2"
4:"Examining [tttTTT], length=6"
3:"'T' (hex=# 54h) is different at pos 4"
2:"Examining [4444 4444k], length=9"
1:"' ' (hex=# 20h) is different at pos 5"

Ruby

strings = ["", "   ", "2", "333", ".55", "tttTTT", "4444   444k", "pépé", "🐶🐶🐺🐶", "🎄🎄🎄🎄"]

strings.each do |str|
  pos = str.empty? ? nil : str =~ /[^#{str[0]}]/
  print "#{str.inspect}  (size #{str.size}): "
  puts pos ? "first different char #{str[pos].inspect} (#{'%#x' % str[pos].ord}) at position #{pos}." : "all the same."
end
Output:
""  (size 0): all the same.
"   "  (size 3): all the same.
"2"  (size 1): all the same.
"333"  (size 3): all the same.
".55"  (size 3): first different char "5" (0x35) at position 1.
"tttTTT"  (size 6): first different char "T" (0x54) at position 3.
"4444   444k"  (size 11): first different char " " (0x20) at position 4.
"pépé"  (size 4): first different char "é" (0xe9) at position 1.
"🐶🐶🐺🐶"  (size 4): first different char "🐺" (0x1f43a) at position 2.
"🎄🎄🎄🎄"  (size 4): all the same.

Rust

fn test_string(input: &str) {
    println!("Checking string {:?} of length {}:", input, input.chars().count());

    let mut chars = input.chars();

    match chars.next() {
        Some(first) => {
            if let Some((character, pos)) = chars.zip(2..).filter(|(c, _)| *c != first).next() {
                println!("\tNot all characters are the same.");
                println!("\t{:?} (0x{:X}) at position {} differs.", character, character as u32, pos);

                return;
            }
        },
        None => {}
    }

    println!("\tAll characters in the string are the same");
}

fn main() {
    let tests = ["", "   ", "2", "333", ".55", "tttTTT", "4444 444k", "pépé", "🐶🐶🐺🐶", "🎄🎄🎄🎄"];

    for string in &tests {
        test_string(string);
    }
}
Output:
Checking string "" of length 0:
        All characters in the string are the same
Checking string "   " of length 3:
        All characters in the string are the same
Checking string "2" of length 1:
        All characters in the string are the same
Checking string "333" of length 3:
        All characters in the string are the same
Checking string ".55" of length 3:
        Not all characters are the same.
        '5' (0x35) at position 2 differs.
Checking string "tttTTT" of length 6:
        Not all characters are the same.
        'T' (0x54) at position 4 differs.
Checking string "4444 444k" of length 9:
        Not all characters are the same.
        ' ' (0x20) at position 5 differs.
Checking string "pépé" of length 4:
        Not all characters are the same.
        'é' (0xE9) at position 2 differs.
Checking string "🐶🐶🐺🐶" of length 4:
        Not all characters are the same.
        '🐺' (0x1F43A) at position 3 differs.
Checking string "🎄🎄🎄🎄" of length 4:
        All characters in the string are the same

S-BASIC

comment
  Return 0 if all the characters in s are the same
  (including the special case of an empty string),
  otherwise the first position where a character
  differs from the preceeding one(s)
end
function samechars(s = string) = integer
   var i, slen, result = integer
   slen = len(s) 
   i = 1
   while i < slen and mid(s,i,1) = mid(s,i+1,1) do
      i = i+1
   if i = slen or slen = 0 then
      result = 0
   else
      result = i+1
end = result

procedure report(str = string)
   var p = integer
   print "Test string "; chr(34); str; chr(34); \
      " has length ="; len(str)
   p = samechars(str)
   if p = 0 then
      print "The characters are all the same"
   else
      print "Characters differ starting at position";p;" ('"; \
      mid(str,p,1);"'=";right$(hex$(asc(mid(str,p,1))),2);"h)"
   print
end

rem - apply to the test cases

report ""
report "   "
report "2"
report "333"
report ".55"
report "tttTTT"
report "4444 444k"

end
Output:
Test string "" has length = 0
The characters are all the same

Test string "   " has length = 0
The characters are all the same

Test string "2" has length = 1
The characters are all the same

Test string "333" has length = 3
The characters are all the same

Test string ".55" has length = 3
Characters differ starting at position 2 ('5'=35h)

Test string "tttTTT" has length = 6
Characters differ starting at position 4 ('T'=54h)

Test string "4444 444k" has length = 9
Characters differ starting at position 5 (' '=20h)

Scala

import scala.collection.immutable.ListMap

object StringAllSameCharacters {

  /**Transform an input String into an HashMap of its characters and its first occurrence index*/
  def countChar( s : String) : Map[Char, Int] = {
    val mapChar = s.toSeq.groupBy(identity).map{ case (a,b) => a->s.indexOf(a) }
    val orderedMapChar = ListMap(mapChar.toSeq.sortWith(_._2 < _._2):_*)
    orderedMapChar
  }

  /**Check if all the characters of a String are the same given an input Hashmap of it */
  def areAllCharEquals ( mapChar : Map[Char, Int] ) : Boolean = {
    return mapChar.size <= 1
  }

  /**Retrieve the first "breaking" different character of a String*/
  def findFirstDifferentChar ( mapChar : Map[Char, Int] ) : Char = {
    if(areAllCharEquals(mapChar) == false) mapChar.keys.toList(1)
    else 0.toChar
  }

  /**Convert char to hexadecimal values as "0xHEXVALUE" */
  def charToHexString ( c : Char) : String = "0x" + c.toHexString

  /**Display results as asked in the ask*/
  def reportResults( s : String) : String = {
    val mapChar = countChar(s)
    if (areAllCharEquals(mapChar)) s + " -- length " + s.size + " -- contains all the same character."
    else {
      val diffChar = findFirstDifferentChar(mapChar)
      s + " -- length " + s.size + 
        " -- contains a different character at index " + 
        (s.indexOf(diffChar).toInt+1).toString + " : " + charToHexString(diffChar)
    }
  }

  def main(args: Array[String]): Unit = {
    println(reportResults(""))
    println(reportResults("   "))
    println(reportResults("2"))
    println(reportResults("333"))
    println(reportResults(".55"))
    println(reportResults("tttTTT"))
    println(reportResults("4444 444k"))
  }


}
Output:
 -- length 0 -- contains all the same character.
    -- length 3 -- contains all the same character.
2 -- length 1 -- contains all the same character.
333 -- length 3 -- contains all the same character.
.55 -- length 3 -- contains a different character at index 2 : 0x35
tttTTT -- length 6 -- contains a different character at index 4 : 0x54
4444 444k -- length 9 -- contains a different character at index 5 : 0x20

Sidef

func analyze_string(str) {
    var chars = str.chars
    chars.range.to_a.each_cons(2, {|a,b|
        chars[a] == chars[b] || return b
    })
    return str.len
}

var strings = ["", "   ", "2", "333", ".55", "tttTTT", "4444   444k", "pépé", "🐶🐶🐺🐶", "🎄🎄🎄🎄"]

strings.each {|str|
    print "'#{str}' (size #{str.len}): "
    var idx = analyze_string(str)

    if (idx == str.len) {
        say "all the same."
    }
    else {
        say "first different char '#{str[idx]}' (#{'%#x' % str[idx].ord}) at position #{idx}."
    }
}
Output:
'' (size 0): all the same.
'   ' (size 3): all the same.
'2' (size 1): all the same.
'333' (size 3): all the same.
'.55' (size 3): first different char '5' (0x35) at position 1.
'tttTTT' (size 6): first different char 'T' (0x54) at position 3.
'4444   444k' (size 11): first different char ' ' (0x20) at position 4.
'pépé' (size 4): first different char 'é' (0xe9) at position 1.
'🐶🐶🐺🐶' (size 4): first different char '🐺' (0x1f43a) at position 2.
'🎄🎄🎄🎄' (size 4): all the same.

SQL

Works with: ORACLE 19c

This is not a particularly efficient solution, but it gets the job done.

/*
This code is an implementation of "Determination if a string has all the same characters" in SQL ORACLE 19c 
p_in_str -- input string
*/
with
  function same_characters_in_string(p_in_str in varchar2) return varchar2 is
    v_que varchar2(32767) := p_in_str;
    v_res varchar2(32767);
    v_first varchar2(1);
    v_next  varchar2(1);
begin
  v_first := substr(v_que,1,1);
  if v_first is null then 
    v_res := '"" length:0 all characters are the same';
  else
    for i in 2..length(v_que)
    loop
      v_next := substr(v_que,i,1); 
      if v_first != v_next then
        v_res := '"'||v_que||'" length:'||length(v_que)||', first different character "'||v_next||'"(0x'||rawtohex(utl_raw.cast_to_raw(v_next))||') at position:'|| i;
        exit;    
      end if;     
   end loop;
   v_res := nvl(v_res,'"'||v_que||'" length:'||length(v_que)||' all characters are the same');
  end if; 
  return v_res;
end;

--Test
select same_characters_in_string('') as res from dual
union all 
select same_characters_in_string('   ') as res from dual
union all 
select same_characters_in_string('2') as res from dual
union all 
select same_characters_in_string('333') as res from dual
union all
select same_characters_in_string('.55') as res from dual
union all
select same_characters_in_string('tttTTT') as res from dual
union all 
select same_characters_in_string('4444 444k') as res from dual
;
Output:
"" length:0 all characters are the same
"   " length:3 all characters are the same
"2" length:1 all characters are the same
"333" length:3 all characters are the same
".55" length:3, first different character "5"(0x35) at position:2
"tttTTT" length:6, first different character "T"(0x54) at position:4
"4444 444k" length:9, first different character " "(0x20) at position:5

Standard ML

datatype result=allSame | difference of string*char*int ;
val chkstring =  fn input =>
let
val rec chk =  fn ([],n)     => allSame
               |  ([x],n)    => allSame
	       |  (x::y::t,n)=> if x=y then chk (y::t,n+1)
	                                else difference (Int.fmt StringCvt.HEX(Char.ord(y)),y,n)
in
(  input,  String.size input ,   chk ( String.explode  input,2 )  )
end;

result (string, string length, same or (hex,char,position))

- map chkstring [ "","   ","1","333",".55","tttTTT","4444 444k" ];
val it =
   [("", 0, allSame), ("   ", 3, allSame), ("1", 1, allSame),
    ("333", 3, allSame), (".55", 3, difference ("35", #"5", 2)),
    ("tttTTT", 6, difference ("54", #"T", 4)),
    ("4444 444k", 9, difference ("20", #" ", 5))]:

Tcl

package require Tcl 8.6 ; # For binary encode

array set yesno {1 Yes 0 No}

set test {
    {}
    {   }
    {2}
    {333}
    {.55}
    {tttTTT}
    {4444 444k}
    {jjjjjjj}
}

# Loop through test strings
foreach str $test {
    set chars [dict create] ; # init dictionary
    set same 1
    set prev {}
    # Loop through characters in string
    for {set i 0} {$i < [string length $str]} {incr i} {
        set c [string index $str $i] ; # get char at index
        if {$prev == {}} {
            set prev $c ; # initialize prev if it doesn't exist
        }
        if {$c != $prev} {
            set same 0
            break ; # Found a different char, break out of the loop
        }
    }

    # Handle Output
    puts [format "Tested: %12s (len: %2d). All Same? %3s. " \
              "'$str'" [string length $str] $yesno($same)]
    if {! $same} {
        puts [format " --> Different character '%s' (hex: 0x%s) appears at index: %s." \
                  $c [binary encode hex $c] $i]
    }
}
Output:
Tested:           '' (len:  0). All Same? Yes.
Tested:        '   ' (len:  3). All Same? Yes.
Tested:          '2' (len:  1). All Same? Yes.
Tested:        '333' (len:  3). All Same? Yes.
Tested:        '.55' (len:  3). All Same?  No.
 --> Different character '5' (hex: 0x35) appears at index: 1.
Tested:     'tttTTT' (len:  6). All Same?  No.
 --> Different character 'T' (hex: 0x54) appears at index: 3.
Tested:  '4444 444k' (len:  9). All Same?  No.
 --> Different character ' ' (hex: 0x20) appears at index: 4.
Tested:    'jjjjjjj' (len:  7). All Same? Yes.

VBA

Instr is a VBA Function which process the strings from left─to─right.

The Optional argument LowerUpper As Boolean can display True for "tttTTT", if you want.

SameCharacters("tttTTT", respons, False) or SameCharacters("tttTTT", respons) return False

SameCharacters("tttTTT", respons, True) return True (All characters are the same)

Sub Main_SameCharacters()
Dim arr, i As Integer, respons As Integer
    arr = Array("", "   ", "2", "333", ".55", "tttTTT", "4444 444k", "111111112", " 123")
    For i = LBound(arr) To UBound(arr)
        If SameCharacters(arr(i), respons) Then
            Debug.Print "Analyze : [" & arr(i) & "], lenght " & Len(arr(i)) & " : " & " All characters are the same."
        Else
            Debug.Print "Analyze : [" & arr(i) & "], lenght " & Len(arr(i)) & " : " & " is different at position " & respons & ", character = '" & Mid(arr(i), respons, 1) & "', hexa : (0x" & Hex(Asc(Mid(arr(i), respons, 1))) & ")"
        End If
    Next
End Sub
Function SameCharacters(sTxt, resp As Integer, Optional LowerUpper As Boolean = False) As Boolean
Dim A As String, B As String, i As Integer, temp As Integer
    If Len(sTxt) > 1 Then
        If LowerUpper Then
            SameCharacters = UCase(sTxt) = String$(Len(sTxt), UCase(Left$(sTxt, 1)))
        Else
            SameCharacters = sTxt = String$(Len(sTxt), Left$(sTxt, 1))
        End If
        If Not SameCharacters Then resp = InStr(sTxt, Left$(Replace(sTxt, Left$(sTxt, 1), vbNullString), 1))
    Else
        SameCharacters = True
    End If
End Function
Output:
Analyze : [], lenght 0 :  All characters are the same.
Analyze : [   ], lenght 3 :  All characters are the same.
Analyze : [2], lenght 1 :  All characters are the same.
Analyze : [333], lenght 3 :  All characters are the same.
Analyze : [.55], lenght 3 :  is different at position 2, character = '5', hexa : (0x35)
Analyze : [tttTTT], lenght 6 :  is different at position 4, character = 'T', hexa : (0x54)
Analyze : [4444 444k], lenght 9 :  is different at position 5, character = ' ', hexa : (0x20)
Analyze : [111111112], lenght 9 :  is different at position 9, character = '2', hexa : (0x32)
Analyze : [ 123], lenght 4 :  is different at position 2, character = '1', hexa : (0x31)

Visual Basic .NET

Translation of: C#
Module Module1

    Sub Analyze(s As String)
        Console.WriteLine("Examining [{0}] which has a length of {1}:", s, s.Length)
        If s.Length > 1 Then
            Dim b = s(0)
            For i = 1 To s.Length
                Dim c = s(i - 1)
                If c <> b Then
                    Console.WriteLine("    Not all characters in the string are the same.")
                    Console.WriteLine("    '{0}' (0x{1:X02}) is different at position {2}", c, AscW(c), i - 1)
                    Return
                End If
            Next
        End If
        Console.WriteLine("    All characters in the string are the same.")
    End Sub

    Sub Main()
        Dim strs() = {"", "   ", "2", "333", ".55", "tttTTT", "4444 444k"}
        For Each s In strs
            Analyze(s)
        Next
    End Sub

End Module
Output:
Examining [] which has a length of 0:
    All characters in the string are the same.
Examining [   ] which has a length of 3:
    All characters in the string are the same.
Examining [2] which has a length of 1:
    All characters in the string are the same.
Examining [333] which has a length of 3:
    All characters in the string are the same.
Examining [.55] which has a length of 3:
    Not all characters in the string are the same.
    '5' (0x35) is different at position 1
Examining [tttTTT] which has a length of 6:
    Not all characters in the string are the same.
    'T' (0x54) is different at position 3
Examining [4444 444k] which has a length of 9:
    Not all characters in the string are the same.
    ' ' (0x20) is different at position 4

V (Vlang)

Translation of: Go
fn analyze(s string) {
    chars := s.runes()
    le := chars.len
    println("Analyzing $s which has a length of $le:")
    if le > 1 {
        for i in 1..le{
            if chars[i] != chars[i-1] {
                println("  Not all characters in the string are the same.")
                println("  '${chars[i]}' (0x${chars[i]:x}) is different at position ${i+1}.\n")
                return
            }
        }
    }
    println("  All characters in the string are the same.\n")
}
 
fn main() {
    strings := [
        "",
        "   ",
        "2",
        "333",
        ".55",
        "tttTTT",
        "4444 444k",
        "pépé",
        "🐶🐶🐺🐶",
        "🎄🎄🎄🎄"
	]
    for s in strings {
        analyze(s)
    }
}
Output:
Analyzing  which has a length of 0:
  All characters in the string are the same.

Analyzing     which has a length of 3:
  All characters in the string are the same.

Analyzing 2 which has a length of 1:
  All characters in the string are the same.

Analyzing 333 which has a length of 3:
  All characters in the string are the same.

Analyzing .55 which has a length of 3:
  Not all characters in the string are the same.
  '5' (0x35) is different at position 2.

Analyzing tttTTT which has a length of 6:
  Not all characters in the string are the same.
  'T' (0x54) is different at position 4.

Analyzing 4444 444k which has a length of 9:
  Not all characters in the string are the same.
  ' ' (0x20) is different at position 5.

Analyzing pépé which has a length of 4:
  Not all characters in the string are the same.
  'é' (0xe9) is different at position 2.

Analyzing 🐶🐶🐺🐶 which has a length of 4:
  Not all characters in the string are the same.
  '🐺' (0x1f43a) is different at position 3.

Analyzing 🎄🎄🎄🎄 which has a length of 4:
  All characters in the string are the same.

Wren

Translation of: Go
Library: Wren-fmt
import "./fmt" for Conv, Fmt

var analyze = Fn.new { |s|
    var chars = s.codePoints.toList
    var le = chars.count
    System.print("Analyzing %(Fmt.q(s)) which has a length of %(le):")
    if (le > 1) {
        for (i in 1...le) {
            if (chars[i] != chars[i-1]) {
                System.print("  Not all characters in the string are the same.")
                var c = String.fromCodePoint(chars[i])
                var hex = Conv.hex(chars[i])
                System.print("  '%(c)' (0x%(hex)) is different at position %(i+1).\n")
                return
            }
        }
    }
    System.print("  All characters in the string are the same.\n")
}

var strings = [
    "",
    "   ",
    "2",
    "333",
    ".55",
    "tttTTT",
    "4444 444k",
    "pépé",
    "🐶🐶🐺🐶",
    "🎄🎄🎄🎄"
]
for (s in strings) analyze.call(s)
Output:
Analyzing "" which has a length of 0:
  All characters in the string are the same.

Analyzing "   " which has a length of 3:
  All characters in the string are the same.

Analyzing "2" which has a length of 1:
  All characters in the string are the same.

Analyzing "333" which has a length of 3:
  All characters in the string are the same.

Analyzing ".55" which has a length of 3:
  Not all characters in the string are the same.
  '5' (0x35) is different at position 2.

Analyzing "tttTTT" which has a length of 6:
  Not all characters in the string are the same.
  'T' (0x54) is different at position 4.

Analyzing "4444 444k" which has a length of 9:
  Not all characters in the string are the same.
  ' ' (0x20) is different at position 5.

Analyzing "pépé" which has a length of 4:
  Not all characters in the string are the same.
  'é' (0xe9) is different at position 2.

Analyzing "🐶🐶🐺🐶" which has a length of 4:
  Not all characters in the string are the same.
  '🐺' (0x1f43a) is different at position 3.

Analyzing "🎄🎄🎄🎄" which has a length of 4:
  All characters in the string are the same.

XPL0

include xpllib;                 \contains StrLen function

proc    StrSame(S);             \Show if string has same characters
char    S;
int     L, I, J, K;
[L:= StrLen(S);
IntOut(0, L);  Text(0, ":       ^"");  Text(0, S);  ChOut(0, ^");  CrLf(0);
for I:= 0 to L-1 do
    for J:= I+1 to L-1 do
        [if S(I) # S(J) then
                [ChOut(0, \tab\ 9);
                for K:= 0 to J do ChOut(0, ^ );
                Text(0, "^^ Not same character: ");
                ChOut(0, S(J));
                Text(0, ", hex ");
                SetHexDigits(2);
                HexOut(0, S(J));
                CrLf(0);
                return;
                ];
        ];
Text(0, "       All same character");  CrLf(0);
];

[Text(0, "Length");  CrLf(0);
StrSame("");
StrSame("   ");
StrSame("2");
StrSame("333");
StrSame(".55");
StrSame("tttTTT");
StrSame("4444 444k");
]
Output:
Length
0:      ""
        All same character
3:      "   "
        All same character
1:      "2"
        All same character
3:      "333"
        All same character
3:      ".55"
          ^ Not same character: 5, hex 35
6:      "tttTTT"
            ^ Not same character: T, hex 54
9:      "4444 444k"
             ^ Not same character:  , hex 20

zkl

fcn stringSameness(str){  // Does not handle Unicode
   sz,unique,uz := str.len(), str.unique(), unique.len();
   println("Length %d: \"%s\"".fmt(sz,str));
   if(sz==uz or uz==1) println("\tSame character in all positions");
   else
      println("\tDifferent: ",
        unique[1,*].pump(List,
	   'wrap(c){ "'%s' (0x%x)[%d]".fmt(c,c.toAsc(), str.find(c)+1) })
        .concat(", "));
}
testStrings:=T("", "   ", "2", "333", ".55", "tttTTT", "4444 444k");
foreach s in (testStrings){ stringSameness(s) }
Output:
Length 0: ""
	Same character in all positions
Length 3: "   "
	Same character in all positions
Length 1: "2"
	Same character in all positions
Length 3: "333"
	Same character in all positions
Length 3: ".55"
	Different: '5' (0x35)[2]
Length 6: "tttTTT"
	Different: 'T' (0x54)[4]
Length 9: "4444 444k"
	Different: ' ' (0x20)[5], 'k' (0x6b)[9]
Cookies help us deliver our services. By using our services, you agree to our use of cookies.