Determine if a string has all the same characters: Difference between revisions
Determine if a string has all the same characters (view source)
Revision as of 23:28, 26 August 2022
, 1 year agosyntax highlighting fixup automation
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
|||
Line 39:
{{trans|Kotlin}}
<
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)</
{{out}}
Line 78:
=={{header|Action!}}==
<
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</
{{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}}==
<
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;</
{{out}}
Line 186:
=={{header|ALGOL 68}}==
<
# 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</
{{out}}
<pre>
Line 264:
=={{header|Arturo}}==
<
"", " ", "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|."
]</
{{out}}
Line 299:
=={{header|AutoHotkey}}==
<
for key, str in testCases {
MsgBox % "Examining `'" str "`' which has a length of " StrLen(str) ":`n"
Line 318:
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 340:
=={{header|AWK}}==
<syntaxhighlight 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>
{{out}}
<pre>
Line 393:
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
<
20 LET Q$ = CHR$ (34)
30 HOME
Line 418:
240 LET C$ = MID$ (S$,I,1)
250 LET SAME = C$ = ""
260 RETURN</
{{out}}
<pre>
Line 447:
==={{header|GWBASIC}}===
Works with BASICA
<syntaxhighlight lang="gwbasic">
10 'SAVE"SAMECHAR", A
20 DEFINT A-Z
Line 474:
250 WEND
260 IF DC$="" THEN I=1
270 RETURN</
{{out}}
<pre>
Line 493:
==={{header|QuickBASIC}}===
Works with QBASIC, VB-DOS, PDS 7.x
<syntaxhighlight lang="qbasic">
DECLARE SUB DifChar (sString AS STRING, wc AS INTEGER, dc AS STRING)
Line 538:
END SUB
</syntaxhighlight>
{{out}}
<pre>
Line 556:
=={{header|BCPL}}==
<
let diffchar(s) = valof
Line 580:
show("tttTTT")
show("4444 444k")
$)</
{{out}}
<pre>"" (length 0): all the same.
Line 593:
Hex function is pieced together from BQNcrate idioms.
<
Hex←⊏⟜(∾"0A"+⟜↕¨10‿26)16{⌽𝕗|⌊∘÷⟜𝕗⍟(↕1+·⌊𝕗⋆⁼1⌈⊢)}
Line 613:
"tttTTT"
"4444 444k"
⟩</
<syntaxhighlight lang="text">All characters are the same
All characters are the same
All characters are the same
Line 620:
'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'</
=={{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">
#include<string.h>
#include<stdio.h>
Line 659:
}
</syntaxhighlight>
Output :
<pre>
Line 692:
</pre>
===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,
Line 815:
return EXIT_SUCCESS;
}</
{{output}}
Line 855:
=={{header|C sharp|C#}}==
{{trans|D}}
<
namespace AllSame {
Line 883:
}
}
}</
{{out}}
<pre>Examining [] which has a length of 0:
Line 904:
=={{header|C++}}==
<
#include <string>
Line 935:
all_characters_are_the_same("4444 444k");
return 0;
}</
{{out}}
Line 966:
=={{header|Clojure}}==
<syntaxhighlight lang="clojure">
(defn check-all-chars-same [s]
(println (format "String (%s) of len: %d" s (count s)))
Line 985:
"tttTTT"
"4444 444k"])
</syntaxhighlight>
{{out}}
Line 1,010:
(strequ) for auto-test
<
(if (not str) (setf str (list "" " " "2" "333" ".55" "tttTTT" "4444 444k")))
(dolist (s str)
Line 1,018:
(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))))))</
{{out}}
Line 1,030:
=={{header|D}}==
{{trans|Kotlin}}
<
void analyze(string s) {
Line 1,052:
analyze(str);
}
}</
{{out}}
<pre>Examining [] which has a length of 0:
Line 1,074:
{{libheader| System.SysUtils}}
{{Trans|D}}
<syntaxhighlight lang="delphi">
program Determine_if_a_string_has_all_the_same_characters;
Line 1,113:
Analyze(w);
Readln;
end.</
{{out}}
<pre>
Line 1,135:
</pre>
=={{header|Erlang|Erlang}}==
<
-module(string_examples).
-export([examine_all_same/1, all_same_examples/0]).
Line 1,171:
"🎄🎄🎄🎄"],
lists:foreach(fun examine_all_same/1, Strings).
</syntaxhighlight>
{{out}}
<pre>
Line 1,220:
=={{header|F_Sharp|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])
Line 1,236:
allSame "tttTTT"
allSame "4444 444k"
</syntaxhighlight>
{{out}}
<pre>
Line 1,249:
=={{header|Factor}}==
<
: find-diff ( str -- i elt ) dup ?first [ = not ] curry find ;
Line 1,270:
"tttTTT"
"4444 444k"
} [ sameness-report. ] each</
{{out}}
<pre>
Line 1,287:
fancier format statement would eliminate the need for the HEX()
procedure.
<
program demo_verify
implicit none
Line 1,324:
end program demo_verify
</syntaxhighlight>
{{out}}
<pre>
Line 1,342:
=={{header|FreeBASIC}}==
<
input "Enter string: ", s
Line 1,364:
'otherwise, success!
print "All characters are the same."</
{{out}}
Line 1,396:
=={{header|Go}}==
<
import "fmt"
Line 1,432:
analyze(s)
}
}</
{{out}}
Line 1,474:
=={{header|Groovy}}==
{{trans|Java}}
<
static void main(String[] args) {
String[] tests = ["", " ", "2", "333", ".55", "tttTTT", "4444 444k"]
Line 1,495:
println("\tAll characters in the string are the same.")
}
}</
{{out}}
<pre>Examining [] which has a length of 0
Line 1,517:
=={{header|Haskell}}==
<
import Data.List (span)
import Data.Char (ord)
Line 1,548:
c : "' (0x" ++ showHex (ord c) ")" ++ " at char " ++ show (succ n))
(inconsistentChar s)) <$>
samples</
and inconsistentChar could alternatively be defined in terms of ''findIndex'':
<
inconsistentChar :: Eq a => [a] -> Maybe (Int, a)
inconsistentChar [] = Nothing
inconsistentChar xs@(x:_) = findIndex (x /=) xs >>= Just . ((,) <*> (xs !!))</
{{Out}}
<pre> ' ' -> consistent
Line 1,569:
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:
<
task=: {{
if. 1>:#t=. ~.y do.
Line 1,577:
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:
<
all 0 character(s) same in ""
all 3 character(s) same in " "
Line 1,588:
"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"</
=={{header|Java}}==
<
public static void main(String[] args){
String[] tests = {"", " ", "2", "333", ".55", "tttTTT", "4444 444k"};
Line 1,611:
System.out.println("\tAll characters in the string are the same.");
}
}</
{{out}}
Line 1,637:
=={{header|JavaScript}}==
<
const arr = [...s];
const at = arr.findIndex(
Line 1,651:
}
['', ' ', '2', '333', '.55', 'tttTTT', '4444 444k', '🐶🐶🐺🐶', '🎄🎄🎄🎄'].forEach(check)</
{{out}}<pre>
"" => Length:0 Same:true Pos: Char: Hex:
Line 1,667:
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';
Line 1,826:
// MAIN ---
return main()
})();</
{{Out}}
<pre>First inconsistent character:
Line 1,846:
<
def firstdifferent:
Line 1,862:
| [lpad(10), length, ($d == null)] + (if $d then [$d, .[$d:$d+1]] else null end) )
| @tsv
'</
{{out}}
Using as input the (JSON) strings shown in the first column of the output as shown below, the output is:
<syntaxhighlight lang="sh">
length same index char
"" 0 true
Line 1,875:
"4444 444k" 9 false 4
"🐶🐶🐺🐶" 4 false 2 🐺
"🎄🎄🎄🎄" 4 true</
=={{header|Julia}}==
<
function testfunction(strings)
Line 1,902:
"🎄🎄🎄🎄",
])
</
<pre>
String | Length | All Same | First Different(Hex) | Position
Line 1,920:
=={{header|Kotlin}}==
{{trans|Go}}
<
println("Examining [$s] which has a length of ${s.length}:")
if (s.length > 1) {
Line 1,940:
analyze(str)
}
}</
{{out}}
<pre>Examining [] which has a length of 0:
Line 1,961:
=={{header|Lambdatalk}}==
<
{def firstDifferingChar
{def firstDifferingChar.r
Line 1,984:
{firstDifferingChar tttTTT}
-> at position 3 t becomes T
</syntaxhighlight>
=={{header|Lua}}==
<
print(string.format("Examining [%s] which has a length of %d:", s, string.len(s)))
if string.len(s) > 1 then
Line 2,013:
end
main()</
{{out}}
<pre>Examining [] which has a length of 0:
Line 2,034:
=={{header|Maple}}==
<
local i, index;
printf("input: \"%s\", length: %a\n", s, StringTools:-Length(s));
Line 2,056:
CheckSame(".55");
CheckSame("tttTTT");
CheckSame("4444 444k");</
{{out}}
<pre>
Line 2,086:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
AllSameCharacters[s_String] := Module[{c = Characters[s], i = 0, tf},
If[Length[c] > 1,
Line 2,110:
AllSameCharacters[".55"]
AllSameCharacters["tttTTT"]
AllSameCharacters["4444 444k"]</
{{out}}
<pre>input = "", Length = 0, All the same!
Line 2,122:
=={{header|Nanoquery}}==
{{trans|Java}}
<
s = str(s)
println "Examining [" + s + "] which has a length of " + str(len(s)) + ":"
Line 2,146:
for s in tests
analyze(s)
end</
{{out}}
<pre>Examining [] which has a length of 0:
Line 2,167:
=={{header|Nim}}==
<
proc analyze(str: string) =
Line 2,181:
var strings = @["", " ", "2", "333", ".55", "tttTTT", "4444 444k"]
for str in strings:
analyze(str)</
{{out}}
<pre>'': [len: 0] all characters are the same
Line 2,194:
=={{header|OCaml}}==
Original version by [http://rosettacode.org/wiki/User:Vanyamil User:Vanyamil]
<syntaxhighlight lang="ocaml">
(* Task: Determine if a string has all the same characters *)
Line 2,240:
|> List.iter format_answer
;;
</syntaxhighlight>
{{out}}
<pre>
Line 2,260:
=={{header|Pascal}}==
<
{$IFDEF FPC}
{$MODE DELPHI}{$OPTIMIZATION ON,ALL}{$CODEALIGN proc=16}{$ALIGN 16}
Line 2,304:
For i := Low(TestData) to HIgh(TestData) do
OutIsAllSame(TestData[i]);
end.</
<pre>
"" of length 0 contains all the same character
Line 2,316:
=={{header|Perl}}==
<
use warnings;
use feature 'say';
Line 2,352:
say 'the same character in all positions.'
}
}</
{{out}}
<pre>"" (length: 0) has the same character in all positions.
Line 2,385:
=={{header|Phix}}==
<!--<
<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:
<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>
<!--</
{{out}}
<pre>
Line 2,423:
=={{header|PicoLisp}}==
<
(let (Lst (chop Str) C (car Lst) P 2 F)
(prin Str ": ")
Line 2,434:
(equal? "333")
(equal? ".55")
(equal? "tttTTT")</
{{out}}
<pre>
Line 2,445:
=={{header|Plain English}}==
<
Start up.
Show the uniformity of "".
Line 2,473:
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.</
{{out}}
<pre>
Line 2,489:
{{works with|SWI-Prolog|7}}
<
:- system:set_prolog_flag(double_quotes,chars) .
Line 2,545:
.
</syntaxhighlight>
{{out}}
Line 2,580:
{{Works with|Python|3.7}}
<
from itertools import groupby
Line 2,679:
# MAIN ---
if __name__ == '__main__':
main()</
{{Out}}
<pre>First, if any, points of difference:
Line 2,694:
and for very long strings, ''itertools.takewhile'' (here used in the definition of a more general '''span''' function), should be slightly more efficient:
<
from itertools import takewhile
Line 2,784:
# MAIN ---
if __name__ == '__main__':
main()</
Putting itertools aside, we could equivalently define ''inconsistentChar'' as:
<
def inconsistentChar(s):
'''Just the first inconsistent character and its index,
Line 2,796:
(Just(ix) for ix in enumerate(s) if s[0] != ix[1]),
Nothing()
)</
{{Out}}
<pre>Consistency tests of seven strings:
Line 2,810:
=={{header|Quackery}}==
<syntaxhighlight lang="quackery">
[ 0 swap
dup size 0 = iff
Line 2,843:
$ ".55" task
$ "tttTTT" task
$ "4444 444k" task</
{{out}}
Line 2,856:
=={{header|R}}==
<
{
strLength <- nchar(string)
Line 2,920:
print(isAllSame("tttTTT"))
cat("Test: A string of length 9 which contains 4444 444k:\n")
print(isAllSame("4444 444k"))</
{{out}}
<pre>Test: A string of length 0 (an empty string):
Line 2,955:
=={{header|Racket}}==
<
(define (first-non-matching-index l =)
Line 2,971:
(module+ test
(for-each report-string-sameness '("" " " "2" "333" ".55" "tttTTT" "4444 444k")))</
{{out}}
Line 2,987:
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"
my $i = 0;
print "\n{$str.raku} (length: {$str.chars}), has ";
Line 3,012:
"\c[LATIN CAPITAL LETTER A WITH DIAERESIS]\c[COMBINING MACRON]" ~
"\c[LATIN CAPITAL LETTER A WITH DIAERESIS AND MACRON]",
'AАΑꓮ𐌀𐊠Ꭺ'</
{{out}}
<pre>"" (length: 0), has the same character in all positions.
Line 3,049:
=={{header|REXX}}==
<
@chr= ' [character' /* define a literal used for SAY.*/
@all= 'all the same character for string (length' /* " " " " " " */
Line 3,076:
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*/</
{{out|output|text= when using the internal default inputs:}}
<pre>
Line 3,089:
=={{header|Ring}}==
<
nputStr = [""," ","2","333",".55","tttTTT","4444 444k"]
Line 3,107:
? " All characters are the same."
next
</syntaxhighlight>
{{out}}
<pre>
Line 3,127:
=={{header|Ruby}}==
<
strings.each do |str|
Line 3,134:
puts pos ? "first different char #{str[pos].inspect} (#{'%#x' % str[pos].ord}) at position #{pos}." : "all the same."
end
</syntaxhighlight>
{{out}}
<pre>"" (size 0): all the same.
Line 3,149:
=={{header|Rust}}==
<
println!("Checking string {:?} of length {}:", input, input.chars().count());
Line 3,175:
test_string(string);
}
}</
{{out}}
<pre>
Line 3,206:
=={{header|Scala}}==
<
object StringAllSameCharacters {
Line 3,256:
}
</syntaxhighlight>
{{out}}
<pre>
Line 3,269:
=={{header|Sidef}}==
<
var chars = str.chars
chars.range.to_a.each_cons(2, {|a,b|
Line 3,289:
say "first different char '#{str[idx]}' (#{'%#x' % str[idx].ord}) at position #{idx}."
}
}</
{{out}}
<pre>
Line 3,308:
This is not a particularly efficient solution, but it gets the job done.
<syntaxhighlight lang="sql">
/*
This code is an implementation of "Determination if a string has all the same characters" in SQL ORACLE 19c
Line 3,352:
select same_characters_in_string('4444 444k') as res from dual
;
</syntaxhighlight>
{{out}}
Line 3,366:
=={{header|Standard ML}}==
<syntaxhighlight lang="standard ml">
datatype result=allSame | difference of string*char*int ;
val chkstring = fn input =>
Line 3,377:
( input, String.size input , chk ( String.explode input,2 ) )
end;
</syntaxhighlight>
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:
("tttTTT", 6, difference ("54", #"T", 4)),
("4444 444k", 9, difference ("20", #" ", 5))]:
</syntaxhighlight>
=={{header|Tcl}}==
<
array set yesno {1 Yes 0 No}
Line 3,428:
$c [binary encode hex $c] $i]
}
}</
{{out}}
Line 3,454:
SameCharacters("tttTTT", respons, True) return True (All characters are the same)
<syntaxhighlight lang="vb">
Sub Main_SameCharacters()
Dim arr, i As Integer, respons As Integer
Line 3,478:
SameCharacters = True
End If
End Function</
{{out}}
<pre>Analyze : [], lenght 0 : All characters are the same.
Line 3,492:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<
Sub Analyze(s As String)
Line 3,517:
End Sub
End Module</
{{out}}
<pre>Examining [] which has a length of 0:
Line 3,539:
=={{header|Vlang}}==
{{trans|Go}}
<
chars := s.runes()
le := chars.len
Line 3,571:
analyze(s)
}
}</
{{out}}
Line 3,614:
{{trans|Go}}
{{libheader|Wren-fmt}}
<
var analyze = Fn.new { |s|
Line 3,646:
"🎄🎄🎄🎄"
]
for (s in strings) analyze.call(s)</
{{out}}
Line 3,687:
=={{header|XPL0}}==
<
proc StrSame(S); \Show if string has same characters
Line 3,719:
StrSame("tttTTT");
StrSame("4444 444k");
]</
{{out}}
Line 3,741:
=={{header|zkl}}==
<
sz,unique,uz := str.len(), str.unique(), unique.len();
println("Length %d: \"%s\"".fmt(sz,str));
Line 3,750:
'wrap(c){ "'%s' (0x%x)[%d]".fmt(c,c.toAsc(), str.find(c)+1) })
.concat(", "));
}</
<
foreach s in (testStrings){ stringSameness(s) }</
{{out}}
<pre>
|