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

→‎{{header|S-BASIC}}: revamp output display
(→‎{{header|S-BASIC}}: revamp output display)
 
(21 intermediate revisions by 14 users not shown)
Line 39:
{{trans|Kotlin}}
 
<langsyntaxhighlight lang="11l">F analyze(s)
print(‘Examining [’s‘] which has a length of ’s.len‘:’)
I s.len > 1
Line 54:
V strs = [‘’, ‘ ’, ‘2’, ‘333’, ‘.55’, ‘tttTTT’, ‘4444 444k’]
L(s) strs
analyze(s)</langsyntaxhighlight>
 
{{out}}
Line 78:
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">PROC PrintBH(BYTE a)
BYTE ARRAY hex=['0 '1 '2 '3 '4 '5 '6 '7 '8 '9 'A 'B 'C 'D 'E 'F]
 
Line 116:
Test("tttTTT")
Test("4444 444k")
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Determine_if_a_string_has_all_the_same_characters.png Screenshot from Atari 8-bit computer]
Line 136:
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="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
Line 167:
All_Chars_Are_Same ("tttTTT");
All_Chars_Are_Same ("4444 444k");
end Test_All_Chars_Are_Same;</langsyntaxhighlight>
 
{{out}}
Line 186:
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68">BEGIN
# return the position of the first different character in s #
# or UPB s + 1 if all the characters are the same #
Line 249:
show first diff( "4444 444k" );
show first diff( "4444|444k" )
END</langsyntaxhighlight>
{{out}}
<pre>
Line 264:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">strings: [
"", " ", "2", "333", ".55", "tttTTT",
"4444 444k", "pépé", "🐶🐶🐺🐶", "🎄🎄🎄🎄"
Line 283:
if? null? firstNotSame -> print "all the same."
else -> print ~"first different char `|get s firstNotSame|` at position |firstNotSame|."
]</langsyntaxhighlight>
 
{{out}}
Line 299:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">testCases := ["", " ", "2", "333", ".55", "tttTTT", "4444 4444k"]
for key, str in testCases {
MsgBox % "Examining `'" str "`' which has a length of " StrLen(str) ":`n"
Line 318:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 340:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f DETERMINE_IF_A_STRING_HAS_ALL_THE_SAME_CHARACTERS.AWK
BEGIN {
Line 375:
}
function max(x,y) { return((x > y) ? x : y) }
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 393:
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
<langsyntaxhighlight lang="gwbasic"> 10 DATA ""," ","2","333",".55","tttTTT","4444 444k"
20 LET Q$ = CHR$ (34)
30 HOME
Line 418:
240 LET C$ = MID$ (S$,I,1)
250 LET SAME = C$ = ""
260 RETURN</langsyntaxhighlight>
{{out}}
<pre>
Line 445:
"4444 444k" OF LENGTH 9.
</pre>
 
==={{header|GWBASIC}}===
==={{header|Chipmunk Basic}}===
Works with BASICA
{{works with|Chipmunk Basic|3.6.4}}
<lang GWBASIC>
The [[#GW-BASIC|GW-BASIC]] solution works without any changes.
 
==={{header|GW-BASIC}}===
{{works with|BASICA}}
{{works with|PC-BASIC|any}}
{{works with|Chipmunk Basic|3.6.4}}
<syntaxhighlight lang="gwbasic">
10 'SAVE"SAMECHAR", A
20 DEFINT A-Z
Line 474 ⟶ 481:
250 WEND
260 IF DC$="" THEN I=1
270 RETURN</langsyntaxhighlight>
{{out}}
<pre>
Line 493 ⟶ 500:
==={{header|QuickBASIC}}===
Works with QBASIC, VB-DOS, PDS 7.x
<syntaxhighlight lang="qbasic">
<lang QBASIC>
DECLARE SUB DifChar (sString AS STRING, wc AS INTEGER, dc AS STRING)
 
Line 538 ⟶ 545:
END SUB
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 556 ⟶ 563:
 
=={{header|BCPL}}==
<langsyntaxhighlight lang="bcpl">get "libhdr"
 
let diffchar(s) = valof
Line 580 ⟶ 587:
show("tttTTT")
show("4444 444k")
$)</langsyntaxhighlight>
{{out}}
<pre>"" (length 0): all the same.
Line 593 ⟶ 600:
 
Hex function is pieced together from BQNcrate idioms.
<langsyntaxhighlight lang="bqn">Check←=´˘2⊸↕
Hex←⊏⟜(∾"0A"+⟜↕¨10‿26)16{⌽𝕗|⌊∘÷⟜𝕗⍟(↕1+·⌊𝕗⋆⁼1⌈⊢)}
 
{
𝕊 str:
r←Check 2⊸↑⍟(2>0=≠)str
•Out {
∧´r ? "All characters are the same" ;
Line 613 ⟶ 620:
"tttTTT"
"4444 444k"
⟩</langsyntaxhighlight>
<syntaxhighlight lang="text">All characters are the same
All characters are the same
All characters are the same
Line 620 ⟶ 627:
'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'</langsyntaxhighlight>
 
=={{header|C}}==
=== Solution with an index to a table ===
In interactive mode, strings with spaces have to be enclosed in double quotes ("")
<syntaxhighlight lang="c">
<lang C>
#include<string.h>
#include<stdio.h>
Line 659 ⟶ 666:
 
}
</syntaxhighlight>
</lang>
Output :
<pre>
Line 692 ⟶ 699:
</pre>
===Solution with pointers===
<langsyntaxhighlight Clang="c">/**
* 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,
Line 815 ⟶ 822:
 
return EXIT_SUCCESS;
}</langsyntaxhighlight>
 
{{output}}
Line 855 ⟶ 862:
=={{header|C sharp|C#}}==
{{trans|D}}
<langsyntaxhighlight lang="csharp">using System;
 
namespace AllSame {
Line 883 ⟶ 890:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>Examining [] which has a length of 0:
Line 904 ⟶ 911:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <stringstring_view>
 
void all_characters_are_the_same(const std::string&string_view str) {
size_t len = str.length();
std::cout << "input: \"" << str << "\", length: " << len << '\n';
Line 915 ⟶ 922:
if (str[i] != ch) {
std::cout << "Not all characters are the same.\n";
std::cout << "Character '" << str[i] << "' (hex " << std::hex
<< "' (hex " << std::hex << static_cast<unsigned int>(str[i])
<< ") at position " << std::dec << i + 1
<< " is not the same as '" << ch << "'.\n\n";
return;
}
Line 935 ⟶ 942:
all_characters_are_the_same("4444 444k");
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 966 ⟶ 973:
 
=={{header|Clojure}}==
<syntaxhighlight lang="clojure">
<lang Clojure>
(defn check-all-chars-same [s]
(println (format "String (%s) of len: %d" s (count s)))
Line 985 ⟶ 992:
"tttTTT"
"4444 444k"])
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,010 ⟶ 1,017:
(strequ) for auto-test
 
<langsyntaxhighlight lang="lisp">(defun strequ (&rest str)
(if (not str) (setf str (list "" " " "2" "333" ".55" "tttTTT" "4444 444k")))
(dolist (s str)
Line 1,018 ⟶ 1,025:
(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))))))</langsyntaxhighlight>
 
{{out}}
Line 1,030 ⟶ 1,037:
=={{header|D}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="d">import std.stdio;
 
void analyze(string s) {
Line 1,052 ⟶ 1,059:
analyze(str);
}
}</langsyntaxhighlight>
{{out}}
<pre>Examining [] which has a length of 0:
Line 1,074 ⟶ 1,081:
{{libheader| System.SysUtils}}
{{Trans|D}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Determine_if_a_string_has_all_the_same_characters;
 
Line 1,113 ⟶ 1,120:
Analyze(w);
Readln;
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 1,134 ⟶ 1,141:
" " 0x20 is different at position 5
</pre>
=={{header|EasyLang}}==
<syntaxhighlight>
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
</syntaxhighlight>
 
 
=={{header|Erlang|Erlang}}==
<langsyntaxhighlight lang="erlang">
-module(string_examples).
-export([examine_all_same/1, all_same_examples/0]).
Line 1,171 ⟶ 1,220:
"🎄🎄🎄🎄"],
lists:foreach(fun examine_all_same/1, Strings).
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,220 ⟶ 1,269:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
// 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])
Line 1,236 ⟶ 1,285:
allSame "tttTTT"
allSame "4444 444k"
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,249 ⟶ 1,298:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: formatting io kernel math.parser sequences ;
 
: find-diff ( str -- i elt ) dup ?first [ = not ] curry find ;
Line 1,270 ⟶ 1,319:
"tttTTT"
"4444 444k"
} [ sameness-report. ] each</langsyntaxhighlight>
{{out}}
<pre>
Line 1,280 ⟶ 1,329:
"tttTTT" — length 6 — contains a different character at index 3: 'T' (0x54)
"4444 444k" — length 9 — contains a different character at index 4: ' ' (0x20)
</pre>
=={{header|Forth}}==
<syntaxhighlight lang="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?
</syntaxhighlight>
{{out}}
<pre>
"" 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
</pre>
=={{header|Fortran}}==
Line 1,287 ⟶ 1,367:
fancier format statement would eliminate the need for the HEX()
procedure.
<langsyntaxhighlight lang="fortran">
program demo_verify
implicit none
Line 1,324 ⟶ 1,404:
 
end program demo_verify
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,342 ⟶ 1,422:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">dim as string s, nxt
 
input "Enter string: ", s
Line 1,364 ⟶ 1,444:
 
'otherwise, success!
print "All characters are the same."</langsyntaxhighlight>
 
{{out}}
Line 1,396 ⟶ 1,476:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,432 ⟶ 1,512:
analyze(s)
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,474 ⟶ 1,554:
=={{header|Groovy}}==
{{trans|Java}}
<langsyntaxhighlight lang="groovy">class Main {
static void main(String[] args) {
String[] tests = ["", " ", "2", "333", ".55", "tttTTT", "4444 444k"]
Line 1,495 ⟶ 1,575:
println("\tAll characters in the string are the same.")
}
}</langsyntaxhighlight>
{{out}}
<pre>Examining [] which has a length of 0
Line 1,517 ⟶ 1,597:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Numeric (showHex)
import Data.List (span)
import Data.Char (ord)
Line 1,548 ⟶ 1,628:
c : "' (0x" ++ showHex (ord c) ")" ++ " at char " ++ show (succ n))
(inconsistentChar s)) <$>
samples</langsyntaxhighlight>
 
and inconsistentChar could alternatively be defined in terms of ''findIndex'':
 
<langsyntaxhighlight lang="haskell">import Data.List (findIndex)
 
inconsistentChar :: Eq a => [a] -> Maybe (Int, a)
inconsistentChar [] = Nothing
inconsistentChar xs@(x:_) = findIndex (x /=) xs >>= Just . ((,) <*> (xs !!))</langsyntaxhighlight>
{{Out}}
<pre> ' ' -> consistent
Line 1,564 ⟶ 1,644:
'tttTTT' -> inconsistent 'T' (0x54) at char 4
'4444 444' -> inconsistent ' ' (0x20) at char 5</pre>
 
=={{Header|Insitux}}==
 
{{Trans|Clojure}}
 
With a minor change from the Clojure entry - showing <code>^</code> underneath the first inconsistent character.
 
<syntaxhighlight lang="insitux>
(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"])
</syntaxhighlight>
 
{{out}}
 
<pre>
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
</pre>
 
=={{header|J}}==
 
In J, <code>#~.y</code> 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:
 
<langsyntaxhighlight Jlang="j">require'convert'
task=: {{
if. 1>:#t=. ~.y do.
Line 1,577 ⟶ 1,700:
echo '"',ch,'" (hex: ',(hfd 3 u:ch),', character ',j,' of ',(":#y),') differs from previous characters in "',y,'"'
end.
}}</langsyntaxhighlight>
 
And here's the task examples with this approach:
 
<langsyntaxhighlight Jlang="j"> task@>'';' ';'2';'333';'.55';'tttTTT';'4444 444k'
all 0 character(s) same in ""
all 3 character(s) same in " "
Line 1,588 ⟶ 1,711:
"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"</langsyntaxhighlight>
 
=={{header|Java}}==
<syntaxhighlight lang="java">
<lang Java>public class Main{
import java.util.regex.Matcher;
import java.util.regex.Pattern;
</syntaxhighlight>
<syntaxhighlight lang="java">
public static void main(String[] args) {
String[] strings = {
"", " ", "2", "333", ".55", "tttTTT", "5", "4444 444k"
};
for (String string : strings)
System.out.println(printCompare(string));
}
 
static String printCompare(String string) {
String stringA = "'%s' %d".formatted(string, string.length());
Pattern pattern = Pattern.compile("(.)\\1*");
Matcher matcher = pattern.matcher(string);
StringBuilder stringB = new StringBuilder();
/* 'Matcher' works dynamically, so we'll have to denote a change */
boolean difference = false;
char character;
String newline = System.lineSeparator();
while (matcher.find()) {
if (matcher.start() != 0) {
character = matcher.group(1).charAt(0);
stringB.append(newline);
stringB.append(" Char '%s' (0x%x)".formatted(character, (int) character));
stringB.append(" @ index %d".formatted(matcher.start()));
difference = true;
}
}
if (!difference)
stringB.append(newline).append(" All characters are the same");
return stringA + stringB;
}
</syntaxhighlight>
<pre>
'' 0
All characters are the same
' ' 3
All characters are the same
'2' 1
All characters are the same
'333' 3
All characters are the same
'.55' 3
Char '5' (0x35) @ index 1
'tttTTT' 6
Char 'T' (0x54) @ index 3
'5' 1
All characters are the same
'4444 444k' 9
Char ' ' (0x20) @ index 4
Char '4' (0x34) @ index 5
Char 'k' (0x6b) @ index 8
</pre>
<br />
Alternate implementations
<syntaxhighlight lang="java">public class Main{
public static void main(String[] args){
String[] tests = {"", " ", "2", "333", ".55", "tttTTT", "4444 444k"};
Line 1,611 ⟶ 1,792:
System.out.println("\tAll characters in the string are the same.");
}
}</langsyntaxhighlight>
{{out}}
 
Line 1,635 ⟶ 1,816:
</pre>
 
===Using Java 8===
<syntaxhighlight lang="java">
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.");
}
}
 
}
</syntaxhighlight>
{{ out }}
<pre>
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
</pre>
 
=={{header|JavaScript}}==
<langsyntaxhighlight JavaScriptlang="javascript">const check = s => {
const arr = [...s];
const at = arr.findIndex(
Line 1,651 ⟶ 1,882:
}
 
['', ' ', '2', '333', '.55', 'tttTTT', '4444 444k', '🐶🐶🐺🐶', '🎄🎄🎄🎄'].forEach(check)</langsyntaxhighlight>
{{out}}<pre>
"" => Length:0 Same:true Pos: Char: Hex:
Line 1,667 ⟶ 1,898:
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).
 
<langsyntaxhighlight lang="javascript">(() => {
'use strict';
Line 1,826 ⟶ 2,057:
// MAIN ---
return main()
})();</langsyntaxhighlight>
{{Out}}
<pre>First inconsistent character:
Line 1,846 ⟶ 2,077:
 
 
<langsyntaxhighlight lang="sh">jq -rn '
 
def firstdifferent:
Line 1,862 ⟶ 2,093:
| [lpad(10), length, ($d == null)] + (if $d then [$d, .[$d:$d+1]] else null end) )
| @tsv
'</langsyntaxhighlight>
{{out}}
Using as input the (JSON) strings shown in the first column of the output as shown below, the output is:
<syntaxhighlight lang="sh">
<lang sh>
length same index char
"" 0 true
Line 1,875 ⟶ 2,106:
"4444 444k" 9 false 4
"🐶🐶🐺🐶" 4 false 2 🐺
"🎄🎄🎄🎄" 4 true</langsyntaxhighlight>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">firstdifferent(s) = isempty(s) ? nothing : findfirst(x -> x != s[1], s)
 
function testfunction(strings)
Line 1,902 ⟶ 2,133:
"🎄🎄🎄🎄",
])
</langsyntaxhighlight>{{out}}
<pre>
String | Length | All Same | First Different(Hex) | Position
Line 1,920 ⟶ 2,151:
=={{header|Kotlin}}==
{{trans|Go}}
<langsyntaxhighlight lang="scala">fun analyze(s: String) {
println("Examining [$s] which has a length of ${s.length}:")
if (s.length > 1) {
Line 1,940 ⟶ 2,171:
analyze(str)
}
}</langsyntaxhighlight>
{{out}}
<pre>Examining [] which has a length of 0:
Line 1,961 ⟶ 2,192:
 
=={{header|Lambdatalk}}==
<langsyntaxhighlight lang="scheme">
{def firstDifferingChar
{def firstDifferingChar.r
Line 1,984 ⟶ 2,215:
{firstDifferingChar tttTTT}
-> at position 3 t becomes T
</syntaxhighlight>
</lang>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="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
Line 2,013 ⟶ 2,244:
end
 
main()</langsyntaxhighlight>
{{out}}
<pre>Examining [] which has a length of 0:
Line 2,034 ⟶ 2,265:
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">CheckSame:=proc(s)
local i, index;
printf("input: \"%s\", length: %a\n", s, StringTools:-Length(s));
Line 2,056 ⟶ 2,287:
CheckSame(".55");
CheckSame("tttTTT");
CheckSame("4444 444k");</langsyntaxhighlight>
{{out}}
<pre>
Line 2,086 ⟶ 2,317:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">ClearAll[AllSameCharacters]
AllSameCharacters[s_String] := Module[{c = Characters[s], i = 0, tf},
If[Length[c] > 1,
Line 2,110 ⟶ 2,341:
AllSameCharacters[".55"]
AllSameCharacters["tttTTT"]
AllSameCharacters["4444 444k"]</langsyntaxhighlight>
{{out}}
<pre>input = "", Length = 0, All the same!
Line 2,122 ⟶ 2,353:
=={{header|Nanoquery}}==
{{trans|Java}}
<langsyntaxhighlight lang="nanoquery">def analyze(s)
s = str(s)
println "Examining [" + s + "] which has a length of " + str(len(s)) + ":"
Line 2,146 ⟶ 2,377:
for s in tests
analyze(s)
end</langsyntaxhighlight>
{{out}}
<pre>Examining [] which has a length of 0:
Line 2,167 ⟶ 2,398:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import strformat
 
proc analyze(str: string) =
Line 2,181 ⟶ 2,412:
var strings = @["", " ", "2", "333", ".55", "tttTTT", "4444 444k"]
for str in strings:
analyze(str)</langsyntaxhighlight>
{{out}}
<pre>'': [len: 0] all characters are the same
Line 2,194 ⟶ 2,425:
=={{header|OCaml}}==
Original version by [http://rosettacode.org/wiki/User:Vanyamil User:Vanyamil]
<syntaxhighlight lang="ocaml">
<lang OCaml>
(* Task: Determine if a string has all the same characters *)
 
Line 2,240 ⟶ 2,471:
|> List.iter format_answer
;;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,260 ⟶ 2,491:
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">program SameNessOfChar;
{$IFDEF FPC}
{$MODE DELPHI}{$OPTIMIZATION ON,ALL}{$CODEALIGN proc=16}{$ALIGN 16}
Line 2,304 ⟶ 2,535:
For i := Low(TestData) to HIgh(TestData) do
OutIsAllSame(TestData[i]);
end.</langsyntaxhighlight>{{out}}
<pre>
"" of length 0 contains all the same character
Line 2,316 ⟶ 2,547:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use feature 'say';
Line 2,352 ⟶ 2,583:
say 'the same character in all positions.'
}
}</langsyntaxhighlight>
{{out}}
<pre>"" (length: 0) has the same character in all positions.
Line 2,385 ⟶ 2,616:
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">samechar</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
Line 2,407 ⟶ 2,638:
<span style="color: #7060A8;">utf8_to_utf32</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"🐶🐶🐺🐶"</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">utf8_to_utf32</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"🎄🎄🎄🎄"</span><span style="color: #0000FF;">)}</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span> <span style="color: #000000;">samechar</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span> <span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,423 ⟶ 2,654:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de equal? (Str)
(let (Lst (chop Str) C (car Lst) P 2 F)
(prin Str ": ")
Line 2,434 ⟶ 2,665:
(equal? "333")
(equal? ".55")
(equal? "tttTTT")</langsyntaxhighlight>
{{out}}
<pre>
Line 2,445 ⟶ 2,676:
 
=={{header|Plain English}}==
<langsyntaxhighlight lang="plainenglish">To run:
Start up.
Show the uniformity of "".
Line 2,473 ⟶ 2,704:
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.</langsyntaxhighlight>
{{out}}
<pre>
Line 2,489 ⟶ 2,720:
{{works with|SWI-Prolog|7}}
 
<langsyntaxhighlight lang="prolog">
:- system:set_prolog_flag(double_quotes,chars) .
 
Line 2,545 ⟶ 2,776:
.
 
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,580 ⟶ 2,811:
 
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''Determine if a string has all the same characters'''
 
from itertools import groupby
Line 2,679 ⟶ 2,910:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>First, if any, points of difference:
Line 2,694 ⟶ 2,925:
and for very long strings, ''itertools.takewhile'' (here used in the definition of a more general '''span''' function), should be slightly more efficient:
 
<langsyntaxhighlight lang="python">'''Determine if a string has all the same characters'''
 
from itertools import takewhile
Line 2,784 ⟶ 3,015:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
 
Putting itertools aside, we could equivalently define ''inconsistentChar'' as:
 
<langsyntaxhighlight lang="python"># inconsistentChar :: String -> Maybe (Int, Char)
def inconsistentChar(s):
'''Just the first inconsistent character and its index,
Line 2,796 ⟶ 3,027:
(Just(ix) for ix in enumerate(s) if s[0] != ix[1]),
Nothing()
)</langsyntaxhighlight>
{{Out}}
<pre>Consistency tests of seven strings:
Line 2,810 ⟶ 3,041:
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery">
<lang Quackery>
[ 0 swap
dup size 0 = iff
Line 2,843 ⟶ 3,074:
$ ".55" task
$ "tttTTT" task
$ "4444 444k" task</langsyntaxhighlight>
 
{{out}}
Line 2,856 ⟶ 3,087:
 
=={{header|R}}==
<langsyntaxhighlight lang="rsplus">isAllSame <- function(string)
{
strLength <- nchar(string)
Line 2,920 ⟶ 3,151:
print(isAllSame("tttTTT"))
cat("Test: A string of length 9 which contains 4444 444k:\n")
print(isAllSame("4444 444k"))</langsyntaxhighlight>
{{out}}
<pre>Test: A string of length 0 (an empty string):
Line 2,955 ⟶ 3,186:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">#lang racket
 
(define (first-non-matching-index l =)
Line 2,971 ⟶ 3,202:
 
(module+ test
(for-each report-string-sameness '("" " " "2" "333" ".55" "tttTTT" "4444 444k")))</langsyntaxhighlight>
 
{{out}}
Line 2,987 ⟶ 3,218:
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.
 
<syntaxhighlight lang="raku" perl6line> -> $str {
my $i = 0;
print "\n{$str.raku} (length: {$str.chars}), has ";
Line 3,012 ⟶ 3,243:
"\c[LATIN CAPITAL LETTER A WITH DIAERESIS]\c[COMBINING MACRON]" ~
"\c[LATIN CAPITAL LETTER A WITH DIAERESIS AND MACRON]",
'AАΑꓮ𐌀𐊠Ꭺ'</langsyntaxhighlight>
{{out}}
<pre>"" (length: 0), has the same character in all positions.
Line 3,049 ⟶ 3,280:
 
=={{header|REXX}}==
<langsyntaxhighlight lang="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' /* " " " " " " */
Line 3,076 ⟶ 3,307:
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*/</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the internal default inputs:}}
<pre>
Line 3,089 ⟶ 3,320:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
nputStr = [""," ","2","333",".55","tttTTT","4444 444k"]
 
Line 3,107 ⟶ 3,338:
? " All characters are the same."
next
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,124 ⟶ 3,355:
Input = '4444 444k', length = 9
First difference at position 5, character = ' '
</pre>
 
=={{header|RPL}}==
{{works with|Halcyon Calc|4.2.7}}
<syntaxhighlight lang="RPL">
≪ 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
</syntaxhighlight>
{{out}}
<pre>
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"
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">strings = ["", " ", "2", "333", ".55", "tttTTT", "4444 444k", "pépé", "🐶🐶🐺🐶", "🎄🎄🎄🎄"]
 
strings.each do |str|
Line 3,134 ⟶ 3,423:
puts pos ? "first different char #{str[pos].inspect} (#{'%#x' % str[pos].ord}) at position #{pos}." : "all the same."
end
</syntaxhighlight>
</lang>
{{out}}
<pre>"" (size 0): all the same.
Line 3,149 ⟶ 3,438:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn test_string(input: &str) {
println!("Checking string {:?} of length {}:", input, input.chars().count());
 
Line 3,175 ⟶ 3,464:
test_string(string);
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,203 ⟶ 3,492:
Checking string "🎄🎄🎄🎄" of length 4:
All characters in the string are the same
</pre>
 
=={{header|S-BASIC}}==
<syntaxhighlight lang = "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
</syntaxhighlight>
{{out}}
<pre>
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)
</pre>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">import scala.collection.immutable.ListMap
 
object StringAllSameCharacters {
Line 3,256 ⟶ 3,614:
}
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,269 ⟶ 3,627:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func analyze_string(str) {
var chars = str.chars
chars.range.to_a.each_cons(2, {|a,b|
Line 3,289 ⟶ 3,647:
say "first different char '#{str[idx]}' (#{'%#x' % str[idx].ord}) at position #{idx}."
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,308 ⟶ 3,666:
This is not a particularly efficient solution, but it gets the job done.
 
<syntaxhighlight lang="sql">
<lang SQL>
/*
This code is an implementation of "Determination if a string has all the same characters" in SQL ORACLE 19c
Line 3,352 ⟶ 3,710:
select same_characters_in_string('4444 444k') as res from dual
;
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,366 ⟶ 3,724:
 
=={{header|Standard ML}}==
<syntaxhighlight lang="standard ml">
<lang Standard ML>
datatype result=allSame | difference of string*char*int ;
val chkstring = fn input =>
Line 3,377 ⟶ 3,735:
( input, String.size input , chk ( String.explode input,2 ) )
end;
</syntaxhighlight>
</lang>
result (string, string length, same or (hex,char,position))
<syntaxhighlight lang="text">
- map chkstring [ ""," ","1","333",".55","tttTTT","4444 444k" ];
val it =
Line 3,386 ⟶ 3,744:
("tttTTT", 6, difference ("54", #"T", 4)),
("4444 444k", 9, difference ("20", #" ", 5))]:
</syntaxhighlight>
</lang>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.6 ; # For binary encode
 
array set yesno {1 Yes 0 No}
Line 3,428 ⟶ 3,786:
$c [binary encode hex $c] $i]
}
}</langsyntaxhighlight>
 
{{out}}
Line 3,454 ⟶ 3,812:
SameCharacters("tttTTT", respons, True) return True (All characters are the same)
 
<syntaxhighlight lang="vb">
<lang vb>
Sub Main_SameCharacters()
Dim arr, i As Integer, respons As Integer
Line 3,478 ⟶ 3,836:
SameCharacters = True
End If
End Function</langsyntaxhighlight>
{{out}}
<pre>Analyze : [], lenght 0 : All characters are the same.
Line 3,492 ⟶ 3,850:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<langsyntaxhighlight lang="vbnet">Module Module1
 
Sub Analyze(s As String)
Line 3,517 ⟶ 3,875:
End Sub
 
End Module</langsyntaxhighlight>
{{out}}
<pre>Examining [] which has a length of 0:
Line 3,537 ⟶ 3,895:
' ' (0x20) is different at position 4</pre>
 
=={{header|V (Vlang)}}==
{{trans|Go}}
<syntaxhighlight lang="v (vlang)">fn analyze(s string) {
chars := s.runes()
le := chars.len
Line 3,571 ⟶ 3,929:
analyze(s)
}
}</langsyntaxhighlight>
 
{{out}}
Line 3,614 ⟶ 3,972:
{{trans|Go}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight ecmascriptlang="wren">import "./fmt" for Conv, Fmt
 
var analyze = Fn.new { |s|
Line 3,646 ⟶ 4,004:
"🎄🎄🎄🎄"
]
for (s in strings) analyze.call(s)</langsyntaxhighlight>
 
{{out}}
Line 3,687 ⟶ 4,045:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include xpllib; \contains StrLen function
 
proc StrSame(S); \Show if string has same characters
Line 3,719 ⟶ 4,077:
StrSame("tttTTT");
StrSame("4444 444k");
]</langsyntaxhighlight>
 
{{out}}
Line 3,741 ⟶ 4,099:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn stringSameness(str){ // Does not handle Unicode
sz,unique,uz := str.len(), str.unique(), unique.len();
println("Length %d: \"%s\"".fmt(sz,str));
Line 3,750 ⟶ 4,108:
'wrap(c){ "'%s' (0x%x)[%d]".fmt(c,c.toAsc(), str.find(c)+1) })
.concat(", "));
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">testStrings:=T("", " ", "2", "333", ".55", "tttTTT", "4444 444k");
foreach s in (testStrings){ stringSameness(s) }</langsyntaxhighlight>
{{out}}
<pre>
18

edits