Split a character string based on change of character: Difference between revisions

Content deleted Content added
Eliasen (talk | contribs)
Frink
Thundergnat (talk | contribs)
m syntax highlighting fixup automation
Line 31: Line 31:
{{trans|C++}}
{{trans|C++}}


<lang 11l>F split(input, delim)
<syntaxhighlight lang="11l">F split(input, delim)
V res = ‘’
V res = ‘’
L(ch) input
L(ch) input
Line 39: Line 39:
R res
R res


print(split(‘gHHH5YY++///\’, ‘, ’))</lang>
print(split(‘gHHH5YY++///\’, ‘, ’))</syntaxhighlight>


{{out}}
{{out}}
Line 47: Line 47:


=={{header|8080 Assembly}}==
=={{header|8080 Assembly}}==
<lang 8080asm> org 100h
<syntaxhighlight lang="8080asm"> org 100h
jmp demo
jmp demo
;;; Split the string under DE on changing characters,
;;; Split the string under DE on changing characters,
Line 76: Line 76:
jmp 5
jmp 5
string: db 'gHHH5YY++///',5Ch,'$'
string: db 'gHHH5YY++///',5Ch,'$'
out: equ $</lang>
out: equ $</syntaxhighlight>
{{out}}
{{out}}
<pre>g, HHH, 5, YY, ++, ///, \</pre>
<pre>g, HHH, 5, YY, ++, ///, \</pre>


=={{header|8086 Assembly}}==
=={{header|8086 Assembly}}==
<lang asm> cpu 8086
<syntaxhighlight lang="asm"> cpu 8086
org 100h
org 100h
section .text
section .text
Line 114: Line 114:
string: db 'gHHH5YY++///\$'
string: db 'gHHH5YY++///\$'
section .bss
section .bss
buf: resb 32</lang>
buf: resb 32</syntaxhighlight>
{{out}}
{{out}}
<pre>g, HHH, 5, YY, ++, ///, \</pre>
<pre>g, HHH, 5, YY, ++, ///, \</pre>
Line 120: Line 120:
=={{header|AArch64 Assembly}}==
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program splitcar64.s */
/* program splitcar64.s */
Line 219: Line 219:
/* for this file see task include a file in language AArch64 assembly */
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
{{Output}}<pre> gg, HHH, 5, YY, ++, ///, \ </pre>
{{Output}}<pre> gg, HHH, 5, YY, ++, ///, \ </pre>


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>PROC Split(CHAR ARRAY s)
<syntaxhighlight lang="action!">PROC Split(CHAR ARRAY s)
BYTE i
BYTE i
CHAR curr,last
CHAR curr,last
Line 251: Line 251:
Test("gHHH5YY++///\")
Test("gHHH5YY++///\")
Test("gHHH 5++,,,///\")
Test("gHHH 5++,,,///\")
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Split_a_character_string_based_on_change_of_character.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Split_a_character_string_based_on_change_of_character.png Screenshot from Atari 8-bit computer]
Line 263: Line 263:


=={{header|Ada}}==
=={{header|Ada}}==
<lang ada>
<syntaxhighlight lang="ada">
with Ada.Text_IO;
with Ada.Text_IO;
procedure Split is
procedure Split is
Line 280: Line 280:
Print_Tokens ("gHHH5YY+++");
Print_Tokens ("gHHH5YY+++");
end split;
end split;
</syntaxhighlight>
</lang>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
<lang algol68>BEGIN
<syntaxhighlight lang="algol68">BEGIN
# returns s with ", " added between each change of character #
# returns s with ", " added between each change of character #
PROC split on characters = ( STRING s )STRING:
PROC split on characters = ( STRING s )STRING:
Line 313: Line 313:


print( ( split on characters( "gHHH5YY++///\" ), newline ) )
print( ( split on characters( "gHHH5YY++///\" ), newline ) )
END</lang>
END</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 320: Line 320:


=={{header|ANSI BASIC}}==
=={{header|ANSI BASIC}}==
<lang ansibasic>REM >split
<syntaxhighlight lang="ansibasic">REM >split
DECLARE EXTERNAL FUNCTION FN_split$
DECLARE EXTERNAL FUNCTION FN_split$


Line 338: Line 338:
NEXT i
NEXT i
LET FN_split$ = split$
LET FN_split$ = split$
END FUNCTION</lang>
END FUNCTION</syntaxhighlight>
{{out}}
{{out}}
<pre>g, HHH, 5, YY, ++, ///, \</pre>
<pre>g, HHH, 5, YY, ++, ///, \</pre>
Line 344: Line 344:
=={{header|APL}}==
=={{header|APL}}==
{{works with|Dyalog APL}}
{{works with|Dyalog APL}}
<lang APL>split ← 2↓∘∊(⊂', '),¨(⊢≠¯1⌽⊢)⊂⊢</lang>
<syntaxhighlight lang="apl">split ← 2↓∘∊(⊂', '),¨(⊢≠¯1⌽⊢)⊂⊢</syntaxhighlight>
{{out}}
{{out}}
<pre> split 'gHHH5YY++///\'
<pre> split 'gHHH5YY++///\'
Line 352: Line 352:
===Functional===
===Functional===
{{Trans|JavaScript}}
{{Trans|JavaScript}}
<lang AppleScript>intercalate(", ", ¬
<syntaxhighlight lang="applescript">intercalate(", ", ¬
map(curry(intercalate)'s |λ|(""), ¬
map(curry(intercalate)'s |λ|(""), ¬
group("gHHH5YY++///\\")))
group("gHHH5YY++///\\")))
Line 468: Line 468:
{}
{}
end if
end if
end tail</lang>
end tail</syntaxhighlight>
{{Out}}
{{Out}}
<pre>g, HHH, 5, YY, ++, ///, \</pre>
<pre>g, HHH, 5, YY, ++, ///, \</pre>
Line 474: Line 474:
===Straightforward===
===Straightforward===
(Also case-sensitve.)
(Also case-sensitve.)
<lang applescript>on splitAtCharacterChanges(input)
<syntaxhighlight lang="applescript">on splitAtCharacterChanges(input)
set len to (count input)
set len to (count input)
if (len < 2) then return input
if (len < 2) then return input
Line 497: Line 497:


-- Test code:
-- Test code:
splitAtCharacterChanges("gHHH5YY++///\\")</lang>
splitAtCharacterChanges("gHHH5YY++///\\")</syntaxhighlight>


{{output}}
{{output}}
<lang applescript>"g, HHH, 5, YY, ++, ///, \\"</lang>
<syntaxhighlight lang="applescript">"g, HHH, 5, YY, ++, ///, \\"</syntaxhighlight>


===ASObjC===
===ASObjC===


<lang applescript>use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
<syntaxhighlight lang="applescript">use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
use framework "Foundation"


Line 514: Line 514:


-- Test code:
-- Test code:
splitAtCharacterChanges("gHHH5YY++///\\")</lang>
splitAtCharacterChanges("gHHH5YY++///\\")</syntaxhighlight>


{{output}}
{{output}}
<lang applescript>"g, HHH, 5, YY, ++, ///, \\"</lang>
<syntaxhighlight lang="applescript">"g, HHH, 5, YY, ++, ///, \\"</syntaxhighlight>


=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
Line 523: Line 523:


{{works with|as|Raspberry Pi}}
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* ARM assembly Raspberry PI */
/* program splitcar.s */
/* program splitcar.s */
Line 641: Line 641:


output : gg, HHH, 5, YY, ++, ///, \
output : gg, HHH, 5, YY, ++, ///, \
</syntaxhighlight>
</lang>


=={{header|Arturo}}==
=={{header|Arturo}}==
<lang rebol>parts: [] current: ""
<syntaxhighlight lang="rebol">parts: [] current: ""
loop split {gHHH5YY++///\} 'ch [
loop split {gHHH5YY++///\} 'ch [
if? or? empty? current
if? or? empty? current
Line 654: Line 654:
]
]
'parts ++ current
'parts ++ current
print parts</lang>
print parts</syntaxhighlight>


{{out}}
{{out}}
Line 661: Line 661:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>Split_Change(str){
<syntaxhighlight lang="autohotkey">Split_Change(str){
for i, v in StrSplit(str)
for i, v in StrSplit(str)
res .= (v=prev) ? v : (res?", " :"") v , prev := v
res .= (v=prev) ? v : (res?", " :"") v , prev := v
return res
return res
}</lang>
}</syntaxhighlight>
Examples:<lang AutoHotkey>str := "gHHH5YY++///\"
Examples:<syntaxhighlight lang="autohotkey">str := "gHHH5YY++///\"
MsgBox % Split_Change(str)</lang>
MsgBox % Split_Change(str)</syntaxhighlight>
Outputs:<pre>g, HHH, 5, YY, ++, ///, \</pre>
Outputs:<pre>g, HHH, 5, YY, ++, ///, \</pre>
===RegEx Version===
===RegEx Version===
<lang AutoHotkey>Split_Change(str){
<syntaxhighlight lang="autohotkey">Split_Change(str){
return RegExReplace(str, "(.)\1*(?!$)", "$0, ")
return RegExReplace(str, "(.)\1*(?!$)", "$0, ")
}</lang>
}</syntaxhighlight>
Examples:<lang AutoHotkey>str := "gHHH5YY++///\"
Examples:<syntaxhighlight lang="autohotkey">str := "gHHH5YY++///\"
MsgBox % Split_Change(str)</lang>
MsgBox % Split_Change(str)</syntaxhighlight>
Outputs:<pre>g, HHH, 5, YY, ++, ///, \</pre>
Outputs:<pre>g, HHH, 5, YY, ++, ///, \</pre>


=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f SPLIT_A_CHARACTER_STRING_BASED_ON_CHANGE_OF_CHARACTER.AWK
# syntax: GAWK -f SPLIT_A_CHARACTER_STRING_BASED_ON_CHANGE_OF_CHARACTER.AWK
BEGIN {
BEGIN {
Line 697: Line 697:
return(new_str)
return(new_str)
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 706: Line 706:
=={{header|BaCon}}==
=={{header|BaCon}}==
Literal strings in BaCon are passed to the C compiler as they are; a backslash therefore needs to be escaped.
Literal strings in BaCon are passed to the C compiler as they are; a backslash therefore needs to be escaped.
<lang freebasic>txt$ = "gHHH5YY++///\\"
<syntaxhighlight lang="freebasic">txt$ = "gHHH5YY++///\\"


c$ = LEFT$(txt$, 1)
c$ = LEFT$(txt$, 1)
Line 717: Line 717:
END IF
END IF
PRINT d$;
PRINT d$;
NEXT</lang>
NEXT</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 724: Line 724:


=={{header|BASIC256}}==
=={{header|BASIC256}}==
<lang freebasic>function split$(instring$)
<syntaxhighlight lang="freebasic">function split$(instring$)
if length(instring$) < 2 then return instring$
if length(instring$) < 2 then return instring$
ret$ = left(instring$,1)
ret$ = left(instring$,1)
Line 734: Line 734:
end function
end function


print split$("gHHH5YY++///\")</lang>
print split$("gHHH5YY++///\")</syntaxhighlight>


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
<lang bbcbasic>REM >split
<syntaxhighlight lang="bbcbasic">REM >split
PRINT FN_split( "gHHH5YY++///\" )
PRINT FN_split( "gHHH5YY++///\" )
END
END
Line 753: Line 753:
split$ += d$
split$ += d$
NEXT
NEXT
= split$</lang>
= split$</syntaxhighlight>
{{out}}
{{out}}
<pre>g, HHH, 5, YY, ++, ///, \</pre>
<pre>g, HHH, 5, YY, ++, ///, \</pre>


=={{header|C}}==
=={{header|C}}==
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#include <string.h>
#include <string.h>
Line 781: Line 781:
*(counter--)='\0';
*(counter--)='\0';
return realloc(result,strlen(result));
return realloc(result,strlen(result));
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 788: Line 788:


=={{header|C sharp}}==
=={{header|C sharp}}==
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Linq;
using System.Linq;
using System.Collections.Generic;
using System.Collections.Generic;
Line 819: Line 819:


public static string Delimit<T>(this IEnumerable<T> source, string separator = "") => string.Join(separator ?? "", source);
public static string Delimit<T>(this IEnumerable<T> source, string separator = "") => string.Join(separator ?? "", source);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 826: Line 826:


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>
<syntaxhighlight lang="cpp">
// Solution for http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character
// Solution for http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character
#include<string>
#include<string>
Line 843: Line 843:
int main(){
int main(){
std::cout << split("gHHH5 ))YY++,,,///\\", ", ") << std::endl;
std::cout << split("gHHH5 ))YY++,,,///\\", ", ") << std::endl;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>g, HHH, 5, , )), YY, ++, ,,,, ///, \</pre>
<pre>g, HHH, 5, , )), YY, ++, ,,,, ///, \</pre>


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang clojure>(defn print-cchanges [s]
<syntaxhighlight lang="clojure">(defn print-cchanges [s]
(println (clojure.string/join ", " (map first (re-seq #"(.)\1*" s)))))
(println (clojure.string/join ", " (map first (re-seq #"(.)\1*" s)))))


(print-cchanges "gHHH5YY++///\\")
(print-cchanges "gHHH5YY++///\\")
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>g, HHH, 5, YY, ++, ///, \</pre>
<pre>g, HHH, 5, YY, ++, ///, \</pre>


=={{header|CLU}}==
=={{header|CLU}}==
<lang clu>% Split a string based on a change of character
<syntaxhighlight lang="clu">% Split a string based on a change of character
split_on_change = iter (s: string) yields (string)
split_on_change = iter (s: string) yields (string)
part: string := ""
part: string := ""
Line 884: Line 884:
end
end
stream$putl(po, rslt)
stream$putl(po, rslt)
end start_up</lang>
end start_up</syntaxhighlight>
{{out}}
{{out}}
<pre>g, HHH, 5, YYY, ++, ///, \</pre>
<pre>g, HHH, 5, YYY, ++, ///, \</pre>


=={{header|COBOL}}==
=={{header|COBOL}}==
<syntaxhighlight lang="cobol">
<lang COBOL>
identification division.
identification division.
program-id. split-ch.
program-id. split-ch.
Line 951: Line 951:


end program split-ch.
end program split-ch.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 965: Line 965:
=={{header|Common Lisp}}==
=={{header|Common Lisp}}==


<lang lisp>(defun split (string)
<syntaxhighlight lang="lisp">(defun split (string)
(loop :for prev := nil :then c
(loop :for prev := nil :then c
:for c :across string
:for c :across string
Line 971: Line 971:


(split "gHHH5YY++///\\")
(split "gHHH5YY++///\\")
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>g, HHH, 5, YY, ++, ///, \</pre>
<pre>g, HHH, 5, YY, ++, ///, \</pre>
Line 977: Line 977:
Doing more work that what's being ask, the following solution builds a list of strings then output it:
Doing more work that what's being ask, the following solution builds a list of strings then output it:


<lang lisp>(defun split (string)
<syntaxhighlight lang="lisp">(defun split (string)
(flet ((make-buffer ()
(flet ((make-buffer ()
(make-array 0 :element-type 'character :adjustable t :fill-pointer t)))
(make-array 0 :element-type 'character :adjustable t :fill-pointer t)))
Line 991: Line 991:
(format t "~{~A~^, ~}"(nreverse result)))))
(format t "~{~A~^, ~}"(nreverse result)))))


(split "gHHH5YY++///\\")</lang>
(split "gHHH5YY++///\\")</syntaxhighlight>
{{out}}
{{out}}
<pre>g, HHH, 5, YY, ++, ///, \</pre>
<pre>g, HHH, 5, YY, ++, ///, \</pre>


=={{header|Cowgol}}==
=={{header|Cowgol}}==
<lang cowgol>include "cowgol.coh";
<syntaxhighlight lang="cowgol">include "cowgol.coh";


sub split(in: [uint8], buf: [uint8]): (out: [uint8]) is
sub split(in: [uint8], buf: [uint8]): (out: [uint8]) is
Line 1,016: Line 1,016:


print(split("gHHH5YY++//\\", &buf[0]));
print(split("gHHH5YY++//\\", &buf[0]));
print_nl();</lang>
print_nl();</syntaxhighlight>
{{out}}
{{out}}
<pre>g, HHH, 5, YY, ++, //, \</pre>
<pre>g, HHH, 5, YY, ++, //, \</pre>
Line 1,022: Line 1,022:
=={{header|D}}==
=={{header|D}}==


<lang D>import std.stdio;
<syntaxhighlight lang="d">import std.stdio;


void main() {
void main() {
Line 1,036: Line 1,036:
}
}
writeln();
writeln();
}</lang>
}</syntaxhighlight>


{{output}}
{{output}}
Line 1,043: Line 1,043:
=={{header|Dyalect}}==
=={{header|Dyalect}}==


<lang dyalect>func String.SmartSplit() {
<syntaxhighlight lang="dyalect">func String.SmartSplit() {
var c
var c
var str = ""
var str = ""
Line 1,059: Line 1,059:
}
}
print("gHHH5YY++///\\".SmartSplit())</lang>
print("gHHH5YY++///\\".SmartSplit())</syntaxhighlight>


{{out}}
{{out}}
Line 1,067: Line 1,067:
=={{header|EasyLang}}==
=={{header|EasyLang}}==


<lang>a$ = "gHHH5YY++///\\"
<syntaxhighlight lang="text">a$ = "gHHH5YY++///\\"
a$[] = strchars a$
a$[] = strchars a$
cp$ = a$[0]
cp$ = a$[0]
Line 1,077: Line 1,077:
s$ &= c$
s$ &= c$
.
.
print s$</lang>
print s$</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,084: Line 1,084:


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>split = fn str ->
<syntaxhighlight lang="elixir">split = fn str ->
IO.puts " input string: #{str}"
IO.puts " input string: #{str}"
String.graphemes(str)
String.graphemes(str)
Line 1,092: Line 1,092:
end
end


split.("gHHH5YY++///\\")</lang>
split.("gHHH5YY++///\\")</syntaxhighlight>


{{out}}
{{out}}
Line 1,101: Line 1,101:


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>open System.Text.RegularExpressions
<syntaxhighlight lang="fsharp">open System.Text.RegularExpressions
let splitRuns s = Regex("""(.)\1*""").Matches(s) |> Seq.cast<Match> |> Seq.map (fun m -> m.Value) |> Seq.toList
let splitRuns s = Regex("""(.)\1*""").Matches(s) |> Seq.cast<Match> |> Seq.map (fun m -> m.Value) |> Seq.toList
printfn "%A" (splitRuns """gHHH5YY++///\""")</lang>
printfn "%A" (splitRuns """gHHH5YY++///\""")</syntaxhighlight>
{{out}}
{{out}}
<pre>["g"; "HHH"; "5"; "YY"; "++"; "///"; "\"]</pre>
<pre>["g"; "HHH"; "5"; "YY"; "++"; "///"; "\"]</pre>


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USE: splitting.monotonic
<syntaxhighlight lang="factor">USE: splitting.monotonic
"gHHH5YY++///\\"
"gHHH5YY++///\\"
"aaabbccccdeeff" [ [ = ] monotonic-split ", " join print ] bi@</lang>
"aaabbccccdeeff" [ [ = ] monotonic-split ", " join print ] bi@</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,119: Line 1,119:
=={{header|Forth}}==
=={{header|Forth}}==
{{works with|Gforth|0.7.3}}
{{works with|Gforth|0.7.3}}
<lang Forth>CREATE A 0 ,
<syntaxhighlight lang="forth">CREATE A 0 ,
: C@A+ A @ C@ [ 1 CHARS ]L A +! ;
: C@A+ A @ C@ [ 1 CHARS ]L A +! ;
: SPLIT. ( c-addr u --) SWAP A ! A @ C@
: SPLIT. ( c-addr u --) SWAP A ! A @ C@
Line 1,131: Line 1,131:
s" gHHH5YY++///\" TEST
s" gHHH5YY++///\" TEST
s" gHHH5 ))YY++,,,///\" TEST
s" gHHH5 ))YY++,,,///\" TEST
BYE</lang>
BYE</syntaxhighlight>
{{out}}
{{out}}
<pre>input: gHHH5YY++///\
<pre>input: gHHH5YY++///\
Line 1,145: Line 1,145:
If the problem were to be solved by writing a "main line" only, there would have to be a declaration of the text variable there but since a subroutine can receive a CHARACTER variable of any size (the actual size is passed as a secret parameter), this can be dodged.
If the problem were to be solved by writing a "main line" only, there would have to be a declaration of the text variable there but since a subroutine can receive a CHARACTER variable of any size (the actual size is passed as a secret parameter), this can be dodged.


For this example a DO-loop stepping along the text is convenient, but in a larger context it would probably be most useful to work along the text with fingers L1 and L2 marking the start and finish positions of each sequence. <lang Fortran> SUBROUTINE SPLATTER(TEXT) !Print a comma-separated list. Repeated characters constitute one item.
For this example a DO-loop stepping along the text is convenient, but in a larger context it would probably be most useful to work along the text with fingers L1 and L2 marking the start and finish positions of each sequence. <syntaxhighlight lang="fortran"> SUBROUTINE SPLATTER(TEXT) !Print a comma-separated list. Repeated characters constitute one item.
Can't display the inserted commas in a different colour so as not to look like any commas in TEXT.
Can't display the inserted commas in a different colour so as not to look like any commas in TEXT.
CHARACTER*(*) TEXT !The text.
CHARACTER*(*) TEXT !The text.
Line 1,165: Line 1,165:
PROGRAM POKE
PROGRAM POKE
CALL SPLATTER("gHHH5YY++///\") !The example given.
CALL SPLATTER("gHHH5YY++///\") !The example given.
END</lang>
END</syntaxhighlight>
Unfortunately, the syntax highlighter has failed to notice the terminating quote character, presumably because the preceding backslash might be an "escape sequence" trigger, a facility ''not'' used in Fortran text ''literals'' except possibly as a later modernist option.
Unfortunately, the syntax highlighter has failed to notice the terminating quote character, presumably because the preceding backslash might be an "escape sequence" trigger, a facility ''not'' used in Fortran text ''literals'' except possibly as a later modernist option.


Line 1,174: Line 1,174:


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>function split( instring as string ) as string
<syntaxhighlight lang="freebasic">function split( instring as string ) as string
if len(instring) < 2 then return instring
if len(instring) < 2 then return instring
dim as string ret = left(instring,1)
dim as string ret = left(instring,1)
Line 1,182: Line 1,182:
next i
next i
return ret
return ret
end function</lang>
end function</syntaxhighlight>


=={{header|Frink}}==
=={{header|Frink}}==
<lang frink>s = "gHHH5YY++///\\"
<syntaxhighlight lang="frink">s = "gHHH5YY++///\\"
println[join[", ", map[getFunction["first", 1], s =~ %r/((.)\2*)/g]]]</lang>
println[join[", ", map[getFunction["first", 1], s =~ %r/((.)\2*)/g]]]</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,194: Line 1,194:
=={{header|FutureBasic}}==
=={{header|FutureBasic}}==
FB can process either Pascal strings (slowly being deprecated), or Apple's Core Foundation CFStrings (and Objective-C NSStrings). Here's the old-school Pascal string function:
FB can process either Pascal strings (slowly being deprecated), or Apple's Core Foundation CFStrings (and Objective-C NSStrings). Here's the old-school Pascal string function:
<lang>
<syntaxhighlight lang="text">
local fn SplitString( inputStr as Str255 ) as Str255
local fn SplitString( inputStr as Str255 ) as Str255
Str255 resultStr
Str255 resultStr
Line 1,212: Line 1,212:


HandleEvents
HandleEvents
</syntaxhighlight>
</lang>
And here's the recommended CFString counterpart:
And here's the recommended CFString counterpart:
<lang>
<syntaxhighlight lang="text">
local fn SplitString( inputStr as CFStringRef ) as CFStringRef
local fn SplitString( inputStr as CFStringRef ) as CFStringRef
NSUInteger i
NSUInteger i
Line 1,233: Line 1,233:


HandleEvents
HandleEvents
</syntaxhighlight>
</lang>
'''Output for either function:'''
'''Output for either function:'''
<pre>
<pre>
Line 1,241: Line 1,241:
=={{header|Go}}==
=={{header|Go}}==
Treating "character" as a byte:
Treating "character" as a byte:
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,267: Line 1,267:
}
}
return b.String()
return b.String()
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,276: Line 1,276:
=={{header|Haskell}}==
=={{header|Haskell}}==


<lang Haskell>import Data.List (group, intercalate)
<syntaxhighlight lang="haskell">import Data.List (group, intercalate)


main :: IO ()
main :: IO ()
main = putStrLn $ intercalate ", " (group "gHHH5YY++///\\")</lang>
main = putStrLn $ intercalate ", " (group "gHHH5YY++///\\")</syntaxhighlight>


{{Out}}
{{Out}}
Line 1,285: Line 1,285:


or as a hand-written fold:
or as a hand-written fold:
<lang haskell>import Data.List (intercalate)
<syntaxhighlight lang="haskell">import Data.List (intercalate)
import Data.Bool (bool)
import Data.Bool (bool)


Line 1,300: Line 1,300:
main :: IO ()
main :: IO ()
main =
main =
putStrLn $ intercalate ", " $ charGroups "gHHH5YY++///\\"</lang>
putStrLn $ intercalate ", " $ charGroups "gHHH5YY++///\\"</syntaxhighlight>
<pre>g, HHH, 5, YY, ++, ///, \</pre>
<pre>g, HHH, 5, YY, ++, ///, \</pre>


or in terms of '''span''':
or in terms of '''span''':
<lang haskell>import Data.List (intercalate)
<syntaxhighlight lang="haskell">import Data.List (intercalate)


charGroups :: String -> [String]
charGroups :: String -> [String]
Line 1,314: Line 1,314:
main :: IO ()
main :: IO ()
main =
main =
putStrLn $ intercalate ", " $ charGroups "gHHH5YY++///\\"</lang>
putStrLn $ intercalate ", " $ charGroups "gHHH5YY++///\\"</syntaxhighlight>
{{Out}}
{{Out}}
<pre>g, HHH, 5, YY, ++, ///, \</pre>
<pre>g, HHH, 5, YY, ++, ///, \</pre>


=={{header|IS-BASIC}}==
=={{header|IS-BASIC}}==
<lang IS-BASIC>100 LET S$="gHHH5YY++///\"
<syntaxhighlight lang="is-basic">100 LET S$="gHHH5YY++///\"
110 PRINT S$(1);
110 PRINT S$(1);
120 FOR I=2 TO LEN(S$)
120 FOR I=2 TO LEN(S$)
Line 1,325: Line 1,325:
140 PRINT S$(I);
140 PRINT S$(I);
150 NEXT
150 NEXT
160 PRINT</lang>
160 PRINT</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
'''Solution:'''
'''Solution:'''
<lang j>splitChars=: (1 ,~ 2 ~:/\ ]) <;.2 ]
<syntaxhighlight lang="j">splitChars=: (1 ,~ 2 ~:/\ ]) <;.2 ]
delimitChars=: ', ' joinstring splitChars</lang>
delimitChars=: ', ' joinstring splitChars</syntaxhighlight>
'''Example Usage:'''
'''Example Usage:'''
<lang j> delimitChars 'gHHH5YY++///\'
<syntaxhighlight lang="j"> delimitChars 'gHHH5YY++///\'
g, HHH, 5, YY, ++, ///, \</lang>
g, HHH, 5, YY, ++, ///, \</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==


<lang Java>package org.rosettacode;
<syntaxhighlight lang="java">package org.rosettacode;


import java.util.ArrayList;
import java.util.ArrayList;
Line 1,401: Line 1,401:
return output.toString();
return output.toString();
}
}
}</lang>
}</syntaxhighlight>


{{Out}}
{{Out}}
Line 1,409: Line 1,409:
===ES6===
===ES6===
{{Trans|Haskell}}
{{Trans|Haskell}}
<lang JavaScript>(() => {
<syntaxhighlight lang="javascript">(() => {
"use strict";
"use strict";


Line 1,465: Line 1,465:
// MAIN ---
// MAIN ---
return main();
return main();
})();</lang>
})();</syntaxhighlight>
{{Out}}
{{Out}}
<pre>g, HHH, 5, YY, ++, ///, \</pre>
<pre>g, HHH, 5, YY, ++, ///, \</pre>
Line 1,471: Line 1,471:


Or, in terms of a general `span` function:
Or, in terms of a general `span` function:
<lang javascript>(() => {
<syntaxhighlight lang="javascript">(() => {
"use strict";
"use strict";


Line 1,518: Line 1,518:
// MAIN ---
// MAIN ---
return main();
return main();
})();</lang>
})();</syntaxhighlight>
{{Out}}
{{Out}}
<pre>g, HHH, 5, YY, ++, ///, \</pre>
<pre>g, HHH, 5, YY, ++, ///, \</pre>


=={{header|jq}}==
=={{header|jq}}==
<lang jq># input: a string
<syntaxhighlight lang="jq"># input: a string
# output: a stream of runs
# output: a stream of runs
def runs:
def runs:
Line 1,535: Line 1,535:
end;
end;


"gHHH5YY++///\\" | [runs] | join(", ")</lang>
"gHHH5YY++///\\" | [runs] | join(", ")</syntaxhighlight>
{{out}}
{{out}}
Using the -r ("raw output") command-line option of jq:
Using the -r ("raw output") command-line option of jq:
Line 1,544: Line 1,544:


Starting with
Starting with
<lang javascript>#!/usr/bin/env jsish
<syntaxhighlight lang="javascript">#!/usr/bin/env jsish
;'Split a string based on change of character, in Jsish';
;'Split a string based on change of character, in Jsish';


Line 1,565: Line 1,565:
;splitOnChange('aaa');
;splitOnChange('aaa');
;splitOnChange('aaaba');
;splitOnChange('aaaba');
;splitOnChange('gH HH5YY++//,/\\');</lang>
;splitOnChange('gH HH5YY++//,/\\');</syntaxhighlight>


Then
Then
Line 1,574: Line 1,574:
Giving
Giving


<lang javascript>#!/usr/bin/env jsish
<syntaxhighlight lang="javascript">#!/usr/bin/env jsish
;'Split a string based on change of character, in Jsish';
;'Split a string based on change of character, in Jsish';


Line 1,607: Line 1,607:
splitOnChange('gH HH5YY++//,/\') ==> g, H, , HH, 5, YY, ++, //, ,, /, \
splitOnChange('gH HH5YY++//,/\') ==> g, H, , HH, 5, YY, ++, //, ,, /, \
=!EXPECTEND!=
=!EXPECTEND!=
*/</lang>
*/</syntaxhighlight>


Which tests as:
Which tests as:
Line 1,625: Line 1,625:


=={{header|Julia}}==
=={{header|Julia}}==
<lang julia># v0.6
<syntaxhighlight lang="julia"># v0.6
using IterTools
using IterTools


str = "gHHH5YY++///\\"
str = "gHHH5YY++///\\"
sep = map(join, groupby(identity, str))
sep = map(join, groupby(identity, str))
println("string: $str\nseparated: ", join(sep, ", "))</lang>
println("string: $str\nseparated: ", join(sep, ", "))</syntaxhighlight>


{{out}}
{{out}}
Line 1,637: Line 1,637:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.0.6
<syntaxhighlight lang="scala">// version 1.0.6


fun splitOnChange(s: String): String {
fun splitOnChange(s: String): String {
Line 1,651: Line 1,651:
val s = """gHHH5YY++///\"""
val s = """gHHH5YY++///\"""
println(splitOnChange(s))
println(splitOnChange(s))
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,659: Line 1,659:


=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
<lang scheme>
<syntaxhighlight lang="scheme">
{def mysplit
{def mysplit
{def mysplit.r
{def mysplit.r
Line 1,673: Line 1,673:
{mysplit gHHH5YY++///\}
{mysplit gHHH5YY++///\}
-> g HHH 5 YY ++ /// \
-> g HHH 5 YY ++ /// \
</syntaxhighlight>
</lang>


=={{header|Lua}}==
=={{header|Lua}}==
Note that the backslash must be quoted as a double backslash as Lua uses C-like escape sequences.
Note that the backslash must be quoted as a double backslash as Lua uses C-like escape sequences.
<lang Lua>function charSplit (inStr)
<syntaxhighlight lang="lua">function charSplit (inStr)
local outStr, nextChar = inStr:sub(1, 1)
local outStr, nextChar = inStr:sub(1, 1)
for pos = 2, #inStr do
for pos = 2, #inStr do
Line 1,689: Line 1,689:
end
end


print(charSplit("gHHH5YY++///\\"))</lang>
print(charSplit("gHHH5YY++///\\"))</syntaxhighlight>
{{out}}
{{out}}
<pre>g, HHH, 5, YY, ++, ///, \</pre>
<pre>g, HHH, 5, YY, ++, ///, \</pre>
Line 1,695: Line 1,695:
'''Alternative:'''
'''Alternative:'''
Simply scan difference in reverse order and insert delimiter in place, the loop counter i will not update with length of s.
Simply scan difference in reverse order and insert delimiter in place, the loop counter i will not update with length of s.
<lang lua>function splitdiff(s)
<syntaxhighlight lang="lua">function splitdiff(s)
for i=#s,2,-1 do
for i=#s,2,-1 do
if s:sub(i,i)~=s:sub(i-1,i-1) then
if s:sub(i,i)~=s:sub(i-1,i-1) then
Line 1,702: Line 1,702:
end
end
return s
return s
end</lang>
end</syntaxhighlight>


=={{header|Ksh}}==
=={{header|Ksh}}==
<lang ksh>
<syntaxhighlight lang="ksh">
#!/bin/ksh
#!/bin/ksh


Line 1,740: Line 1,740:
print "Original: ${str}"
print "Original: ${str}"
print " Split: $(_splitonchg "${str}" "${delim}")"
print " Split: $(_splitonchg "${str}" "${delim}")"
</syntaxhighlight>
</lang>
{{out}}<pre>
{{out}}<pre>
Original: gHHH5YY++///\
Original: gHHH5YY++///\
Line 1,748: Line 1,748:
Stack New open a new stack object as current stack, and keep the old one. After the end of block execution old stack get back as current stack. Data statement push to bottom (we read from top, so using data we get a FIFO type). Letter$ pops a string or raise an error if no string found at the top of stack.
Stack New open a new stack object as current stack, and keep the old one. After the end of block execution old stack get back as current stack. Data statement push to bottom (we read from top, so using data we get a FIFO type). Letter$ pops a string or raise an error if no string found at the top of stack.


<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module PrintParts(splitthis$) {
Module PrintParts(splitthis$) {
Def string m$, p$
Def string m$, p$
Line 1,770: Line 1,770:
}
}
PrintParts "gHHH5YY++///\"
PrintParts "gHHH5YY++///\"
</syntaxhighlight>
</lang>


=={{header|Maple}}==
=={{header|Maple}}==
Added an additional backlash to escape the \ character at the end.
Added an additional backlash to escape the \ character at the end.
<lang Maple>splitChange := proc(str::string)
<syntaxhighlight lang="maple">splitChange := proc(str::string)
local start,i,len;
local start,i,len;
start := 1;
start := 1;
Line 1,786: Line 1,786:
printf("%s", str[start..len]);
printf("%s", str[start..len]);
end proc;
end proc;
splitChange("gHHH5YY++///\\");</lang>
splitChange("gHHH5YY++///\\");</syntaxhighlight>
{{out}}
{{out}}
<pre>g, HHH, 5, YY, ++, ///, \</pre>
<pre>g, HHH, 5, YY, ++, ///, \</pre>
Line 1,792: Line 1,792:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
The backslash (\) must be escaped with another backslash when defining the string.
The backslash (\) must be escaped with another backslash when defining the string.
<lang Mathematica>StringJoin@@Riffle[StringCases["gHHH5YY++///\\", p : (x_) .. -> p], ", "]</lang>
<syntaxhighlight lang="mathematica">StringJoin@@Riffle[StringCases["gHHH5YY++///\\", p : (x_) .. -> p], ", "]</syntaxhighlight>
{{out}}
{{out}}
<pre>g, HHH, 5, YY, ++, ///, \</pre>
<pre>g, HHH, 5, YY, ++, ///, \</pre>


=={{header|MiniScript}}==
=={{header|MiniScript}}==
<lang MiniScript>s = "gHHH5YY++///\"
<syntaxhighlight lang="miniscript">s = "gHHH5YY++///\"
output = []
output = []
lastLetter = s[0]
lastLetter = s[0]
Line 1,805: Line 1,805:
lastLetter = letter
lastLetter = letter
end for
end for
print output.join("")</lang>
print output.join("")</syntaxhighlight>
{{out}}
{{out}}
<pre>g, HHH, 5, YY, ++, ///, \</pre>
<pre>g, HHH, 5, YY, ++, ///, \</pre>


=={{header|Modula-2}}==
=={{header|Modula-2}}==
<lang modula2>MODULE CharacterChange;
<syntaxhighlight lang="modula2">MODULE CharacterChange;
FROM Terminal IMPORT Write,WriteString,WriteLn,ReadChar;
FROM Terminal IMPORT Write,WriteString,WriteLn,ReadChar;


Line 1,834: Line 1,834:


ReadChar
ReadChar
END CharacterChange.</lang>
END CharacterChange.</syntaxhighlight>
{{out}}
{{out}}
<pre>g
<pre>g
Line 1,845: Line 1,845:


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>proc splitOnDiff(str: string): string =
<syntaxhighlight lang="nim">proc splitOnDiff(str: string): string =
result = ""
result = ""


Line 1,864: Line 1,864:
assert splitOnDiff("""gHHH5YY++///\""") == """g, HHH, 5, YY, ++, ///, \"""
assert splitOnDiff("""gHHH5YY++///\""") == """g, HHH, 5, YY, ++, ///, \"""


echo splitOnDiff("""gHHH5YY++///\""")</lang>
echo splitOnDiff("""gHHH5YY++///\""")</syntaxhighlight>
{{output}}
{{output}}
<pre>g, HHH, 5, YY, ++, ///, \</pre>
<pre>g, HHH, 5, YY, ++, ///, \</pre>


=={{header|ooRexx}}==
=={{header|ooRexx}}==
<lang oorexx>Parse Arg str . /*obtain optional arguments from the CL*/
<syntaxhighlight lang="oorexx">Parse Arg str . /*obtain optional arguments from the CL*/
If str=='' Then str= 'gHHH5YY++///\' /*Not specified? Then use the default.*/
If str=='' Then str= 'gHHH5YY++///\' /*Not specified? Then use the default.*/
i=1
i=1
Line 1,882: Line 1,882:
i=j
i=j
End
End
Say ol</lang>
Say ol</syntaxhighlight>
{{out}}
{{out}}
<pre>g, HHH, 5, YY, ++, ///, \</pre>
<pre>g, HHH, 5, YY, ++, ///, \</pre>
=={{header|Pascal}}==
=={{header|Pascal}}==
<lang pascal>program SplitChars;
<syntaxhighlight lang="pascal">program SplitChars;
{$IFDEF FPC}
{$IFDEF FPC}
{$MODE DELPHI}{$COPERATORS ON}
{$MODE DELPHI}{$COPERATORS ON}
Line 1,917: Line 1,917:
BEGIN
BEGIN
writeln(SplitAtChars(TestString));
writeln(SplitAtChars(TestString));
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>g, HHH, 5, YY, ++, ///, \</pre>
<pre>g, HHH, 5, YY, ++, ///, \</pre>


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>use strict;
<syntaxhighlight lang="perl">use strict;
use warnings;
use warnings;
use feature 'say';
use feature 'say';
Line 1,936: Line 1,936:
}
}
say "Orginal: $string\n Split: 「" . join('」, 「', @S) . "」\n";
say "Orginal: $string\n Split: 「" . join('」, 「', @S) . "」\n";
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Orginal: gHHH5YY++///\
<pre>Orginal: gHHH5YY++///\
Line 1,945: Line 1,945:


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>-->
<!--<syntaxhighlight lang="phix">-->
<span style="color: #008080;">function</span> <span style="color: #000000;">split_on_change</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">split_on_change</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
Line 1,963: Line 1,963:
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">split_on_change</span><span style="color: #0000FF;">(</span><span style="color: #008000;">`gHHH5YY++///\`</span><span style="color: #0000FF;">))</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">split_on_change</span><span style="color: #0000FF;">(</span><span style="color: #008000;">`gHHH5YY++///\`</span><span style="color: #0000FF;">))</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{Out}}
{{Out}}
<pre>
<pre>
Line 1,970: Line 1,970:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(de splitme (Str)
<syntaxhighlight lang="picolisp">(de splitme (Str)
(let (Str (chop Str) Fin)
(let (Str (chop Str) Fin)
(glue
(glue
Line 1,979: Line 1,979:
(conc Fin (cons X))
(conc Fin (cons X))
(link (setq Fin (cons X))) ) ) ) ) ) )
(link (setq Fin (cons X))) ) ) ) ) ) )
(prinl (splitme "gHHH5YY++///\\"))</lang>
(prinl (splitme "gHHH5YY++///\\"))</syntaxhighlight>
{{out}}
{{out}}
<pre>g, HHH, 5, YY, ++, ///, \</pre>
<pre>g, HHH, 5, YY, ++, ///, \</pre>


=={{header|Pike}}==
=={{header|Pike}}==
<syntaxhighlight lang="pike">
<lang Pike>
string input = "gHHH5YY++///\\"; // \ needs escaping
string input = "gHHH5YY++///\\"; // \ needs escaping
string last_char;
string last_char;
Line 1,994: Line 1,994:
}
}


</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 2,004: Line 2,004:


After executing the following code, for example:
After executing the following code, for example:
<lang plainenglish>Put "abcdef" into a string.
<syntaxhighlight lang="plainenglish">Put "abcdef" into a string.
Slap a rider on the string.</lang>
Slap a rider on the string.</syntaxhighlight>


The rider looks like this:
The rider looks like this:
<lang plainenglish>Original: "abcdef"
<syntaxhighlight lang="plainenglish">Original: "abcdef"
Source: "abcdef"
Source: "abcdef"
Token: ""</lang>
Token: ""</syntaxhighlight>


Now when we <code>Bump the rider.</code>, it looks like this:
Now when we <code>Bump the rider.</code>, it looks like this:
<lang plainenglish>Original: "abcdef"
<syntaxhighlight lang="plainenglish">Original: "abcdef"
Source: "bcdef"
Source: "bcdef"
Token: "a"</lang>
Token: "a"</syntaxhighlight>


Another bump, and:
Another bump, and:
<lang plainenglish>Original: "abcdef"
<syntaxhighlight lang="plainenglish">Original: "abcdef"
Source: "cdef"
Source: "cdef"
Token: "ab"</lang>
Token: "ab"</syntaxhighlight>


Now let's say we have a complete token and want to start a new one. We can
Now let's say we have a complete token and want to start a new one. We can
Line 2,026: Line 2,026:
and now the rider looks like this:
and now the rider looks like this:


<lang plainenglish>Original: "abcdef"
<syntaxhighlight lang="plainenglish">Original: "abcdef"
Source: "cdef"
Source: "cdef"
Token: ""</lang>
Token: ""</syntaxhighlight>


And that's all there is to it.
And that's all there is to it.


<lang plainenglish>To run:
<syntaxhighlight lang="plainenglish">To run:
Start up.
Start up.
Split "gHHH5YY++///\" into some string things by change of character.
Split "gHHH5YY++///\" into some string things by change of character.
Line 2,067: Line 2,067:
If the string thing's next is not nil, write ", " on the console without advancing.
If the string thing's next is not nil, write ", " on the console without advancing.
Put the string thing's next into the string thing.
Put the string thing's next into the string thing.
Repeat.</lang>
Repeat.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,075: Line 2,075:
=={{header|PowerShell}}==
=={{header|PowerShell}}==
{{trans|BBC BASIC}}
{{trans|BBC BASIC}}
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Split-String ([string]$String)
function Split-String ([string]$String)
{
{
Line 2,096: Line 2,096:
$splitString
$splitString
}
}
</syntaxhighlight>
</lang>
<syntaxhighlight lang="powershell">
<lang PowerShell>
Split-String "gHHH5YY++///\"
Split-String "gHHH5YY++///\"
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 2,106: Line 2,106:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang purebasic>Procedure splitstring(s$)
<syntaxhighlight lang="purebasic">Procedure splitstring(s$)
Define *p.Character = @s$,
Define *p.Character = @s$,
c_buf.c = *p\c
c_buf.c = *p\c
Line 2,124: Line 2,124:
splitstring("gHHH5YY++///\")
splitstring("gHHH5YY++///\")
Input()
Input()
EndIf</lang>
EndIf</syntaxhighlight>
{{out}}
{{out}}
<pre>g, HHH, 5, YY, ++, ///, \</pre>
<pre>g, HHH, 5, YY, ++, ///, \</pre>
Line 2,132: Line 2,132:
===Python3.6+===
===Python3.6+===
Using [[https://docs.python.org/3.6/library/itertools.html#itertools.groupby itertools.groupby]].
Using [[https://docs.python.org/3.6/library/itertools.html#itertools.groupby itertools.groupby]].
<lang python>from itertools import groupby
<syntaxhighlight lang="python">from itertools import groupby


def splitter(text):
def splitter(text):
Line 2,139: Line 2,139:
if __name__ == '__main__':
if __name__ == '__main__':
txt = 'gHHH5YY++///\\' # Note backslash is the Python escape char.
txt = 'gHHH5YY++///\\' # Note backslash is the Python escape char.
print(f'Input: {txt}\nSplit: {splitter(txt)}')</lang>
print(f'Input: {txt}\nSplit: {splitter(txt)}')</syntaxhighlight>


{{out}}
{{out}}
Line 2,146: Line 2,146:


===Python: Using zip===
===Python: Using zip===
<lang python>def splitterz(text):
<syntaxhighlight lang="python">def splitterz(text):
return (''.join(x + ('' if x == nxt else ', ')
return (''.join(x + ('' if x == nxt else ', ')
for x, nxt in zip(txt, txt[1:] + txt[-1])))
for x, nxt in zip(txt, txt[1:] + txt[-1])))
Line 2,152: Line 2,152:
if __name__ == '__main__':
if __name__ == '__main__':
txt = 'gHHH5YY++///\\'
txt = 'gHHH5YY++///\\'
print(splitterz(txt))</lang>
print(splitterz(txt))</syntaxhighlight>


{{out}}
{{out}}
Line 2,158: Line 2,158:


===Python2===
===Python2===
<lang python>import itertools
<syntaxhighlight lang="python">import itertools


try: input = raw_input
try: input = raw_input
Line 2,168: Line 2,168:
groups.append(''.join(g))
groups.append(''.join(g))
print(' input string: %s' % s)
print(' input string: %s' % s)
print(' output string: %s' % ', '.join(groups))</lang>
print(' output string: %s' % ', '.join(groups))</syntaxhighlight>
{{out}} &nbsp; when using the default input:
{{out}} &nbsp; when using the default input:
<pre>
<pre>
Line 2,176: Line 2,176:


=={{header|Quackery}}==
=={{header|Quackery}}==
<lang Quackery>[ dup size 2 <
<syntaxhighlight lang="quackery">[ dup size 2 <
iff size done
iff size done
behead swap
behead swap
Line 2,191: Line 2,191:
dip [ $ ", " join ]
dip [ $ ", " join ]
recurse join ] is runs$ ( $ --> $ )
recurse join ] is runs$ ( $ --> $ )
</syntaxhighlight>
</lang>
'''Testing in Quackery shell.'''
'''Testing in Quackery shell.'''
<pre>/O> $ "gHHH5YY++///\" runs$ echo$
<pre>/O> $ "gHHH5YY++///\" runs$ echo$
Line 2,201: Line 2,201:
=={{header|Racket}}==
=={{header|Racket}}==
{{trans|Python}}
{{trans|Python}}
<lang racket>#lang racket
<syntaxhighlight lang="racket">#lang racket
(define (split-strings-on-change s)
(define (split-strings-on-change s)
(map list->string (group-by values (string->list s) char=?)))
(map list->string (group-by values (string->list s) char=?)))
Line 2,209: Line 2,209:
<
<
)
)
", "))</lang>
", "))</syntaxhighlight>


{{out}}
{{out}}
Line 2,218: Line 2,218:
{{works with|Rakudo|2017.05}}
{{works with|Rakudo|2017.05}}


<lang perl6>sub group-chars ($str) { $str.comb: / (.) $0* / }
<syntaxhighlight lang="raku" line>sub group-chars ($str) { $str.comb: / (.) $0* / }


# Testing:
# Testing:
Line 2,225: Line 2,225:
put 'Original: ', $string;
put 'Original: ', $string;
put ' Split: ', group-chars($string).join(', ');
put ' Split: ', group-chars($string).join(', ');
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,253: Line 2,253:
=={{header|REXX}}==
=={{header|REXX}}==
===version 1===
===version 1===
<lang rexx>/*REXX program splits a string based on change of character ───► a comma delimited list.*/
<syntaxhighlight lang="rexx">/*REXX program splits a string based on change of character ───► a comma delimited list.*/
parse arg str /*obtain optional arguments from the CL*/
parse arg str /*obtain optional arguments from the CL*/
if str=='' then str= 'gHHH5YY++///\' /*Not specified? Then use the default.*/
if str=='' then str= 'gHHH5YY++///\' /*Not specified? Then use the default.*/
Line 2,263: Line 2,263:
end /*j*/ /* [↓] keep peeling chars until done. */
end /*j*/ /* [↓] keep peeling chars until done. */
say ' input string: ' str /*display the original string & output.*/
say ' input string: ' str /*display the original string & output.*/
say ' output string: ' $ /*stick a fork in it, we're all done. */</lang>
say ' output string: ' $ /*stick a fork in it, we're all done. */</syntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
{{out|output|text=&nbsp; when using the default input:}}
<pre>
<pre>
Line 2,271: Line 2,271:


===version 2===
===version 2===
<lang rexx>/* REXX */
<syntaxhighlight lang="rexx">/* REXX */
Parse arg str /*obtain optional arguments from the CL*/
Parse arg str /*obtain optional arguments from the CL*/
if str=='' then str= 'gHHH5YY++///\' /*Not specified? Then use the default.*/
if str=='' then str= 'gHHH5YY++///\' /*Not specified? Then use the default.*/
Line 2,290: Line 2,290:
result=result||x
result=result||x
say ' input string: ' input
say ' input string: ' input
say ' output string: ' result </lang>
say ' output string: ' result </syntaxhighlight>
{{out]]
{{out]]
<pre> input string: gHHH5YY++///\
<pre> input string: gHHH5YY++///\
Line 2,296: Line 2,296:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
see split("gHHH5YY++///\")
see split("gHHH5YY++///\")


Line 2,311: Line 2,311:
next
next
return split
return split
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 2,318: Line 2,318:


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>def split(str)
<syntaxhighlight lang="ruby">def split(str)
puts " input string: #{str}"
puts " input string: #{str}"
s = str.chars.chunk(&:itself).map{|_,a| a.join}.join(", ")
s = str.chars.chunk(&:itself).map{|_,a| a.join}.join(", ")
Line 2,325: Line 2,325:
end
end


split("gHHH5YY++///\\")</lang>
split("gHHH5YY++///\\")</syntaxhighlight>


{{out}}
{{out}}
Line 2,334: Line 2,334:


=={{header|Rust}}==
=={{header|Rust}}==
<lang Rust>fn splitter(string: &str) -> String {
<syntaxhighlight lang="rust">fn splitter(string: &str) -> String {
let chars: Vec<_> = string.chars().collect();
let chars: Vec<_> = string.chars().collect();
let mut result = Vec::new();
let mut result = Vec::new();
Line 2,367: Line 2,367:
println!("input string: {}", test_string);
println!("input string: {}", test_string);
println!("output string: {}", splitter(test_string));
println!("output string: {}", splitter(test_string));
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,380: Line 2,380:


===Alternate using IterTools===
===Alternate using IterTools===
<lang Rust>use itertools::Itertools;
<syntaxhighlight lang="rust">use itertools::Itertools;


pub fn split_text(s: &str) -> Vec<String> {
pub fn split_text(s: &str) -> Vec<String> {
Line 2,400: Line 2,400:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|Scala}}==
=={{header|Scala}}==
<lang Scala>// Split a (character) string into comma (plus a blank) delimited strings
<syntaxhighlight lang="scala">// Split a (character) string into comma (plus a blank) delimited strings
// based on a change of character (left to right).
// based on a change of character (left to right).
// See https://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character#Scala
// See https://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character#Scala
Line 2,410: Line 2,410:
(s + 'X').sliding(2).map(pair => pair.head + (if (pair.head != pair.last) ", " else "")).mkString("")
(s + 'X').sliding(2).map(pair => pair.head + (if (pair.head != pair.last) ", " else "")).mkString("")


println(runLengthSplit("""gHHH5YY++///\"""))</lang>
println(runLengthSplit("""gHHH5YY++///\"""))</syntaxhighlight>
{{Out}}See it in running in your browser by [https://scalafiddle.io/sf/c4dp8GT/2 ScalaFiddle (JavaScript)]
{{Out}}See it in running in your browser by [https://scalafiddle.io/sf/c4dp8GT/2 ScalaFiddle (JavaScript)]
or by [https://scastie.scala-lang.org/mDoBS77YSG2Z7w5xdAPzcw Scastie (JVM)].
or by [https://scastie.scala-lang.org/mDoBS77YSG2Z7w5xdAPzcw Scastie (JVM)].


<syntaxhighlight lang="scala">
<lang Scala>
def runLengthSplit(s:String):List[String] = {
def runLengthSplit(s:String):List[String] = {
def recursiveSplit(acc:List[String], rest:String): List[String] = rest match {
def recursiveSplit(acc:List[String], rest:String): List[String] = rest match {
Line 2,429: Line 2,429:
val result = runLengthSplit("""gHHH5YY++///\""")
val result = runLengthSplit("""gHHH5YY++///\""")
println(result.mkString(","))
println(result.mkString(","))
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 2,436: Line 2,436:


=={{header|Sed}}==
=={{header|Sed}}==
<lang sed>echo 'gHHH5YY++///\' | sed 's/\(.\)\1*/&, /g;s/, $//'</lang>
<syntaxhighlight lang="sed">echo 'gHHH5YY++///\' | sed 's/\(.\)\1*/&, /g;s/, $//'</syntaxhighlight>
Output:
Output:
g, HHH, 5, YY, ++, ///, \
g, HHH, 5, YY, ++, ///, \


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>func group(str) {
<syntaxhighlight lang="ruby">func group(str) {
gather {
gather {
while (var match = (str =~ /((.)\g{-1}*)/g)) {
while (var match = (str =~ /((.)\g{-1}*)/g)) {
Line 2,449: Line 2,449:
}
}


say group(ARGV[0] \\ 'gHHH5YY++///\\').join(', ')</lang>
say group(ARGV[0] \\ 'gHHH5YY++///\\').join(', ')</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,457: Line 2,457:
=={{header|SNOBOL4}}==
=={{header|SNOBOL4}}==
{{works with|SNOBOL4, SPITBOL for Linux}}
{{works with|SNOBOL4, SPITBOL for Linux}}
<syntaxhighlight lang="snobol4">
<lang SNOBOL4>
* Program: split_on_change_of_character.sbl
* Program: split_on_change_of_character.sbl
* To run: sbl split_on_change_of_character.sbl
* To run: sbl split_on_change_of_character.sbl
Line 2,495: Line 2,495:
output = split_string
output = split_string


END</lang>
END</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,504: Line 2,504:


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<lang sml>(*
<syntaxhighlight lang="sml">(*
* Head-Tail implementation of grouping
* Head-Tail implementation of grouping
*)
*)
Line 2,513: Line 2,513:
fun group xs = group' nil xs
fun group xs = group' nil xs


fun groupString str = String.concatWith ", " (map implode (group (explode str)))</lang>
fun groupString str = String.concatWith ", " (map implode (group (explode str)))</syntaxhighlight>


{{out}}
{{out}}
Line 2,521: Line 2,521:
=={{header|Swift}}==
=={{header|Swift}}==


<lang swift>public extension String {
<syntaxhighlight lang="swift">public extension String {
func splitOnChanges() -> [String] {
func splitOnChanges() -> [String] {
guard !isEmpty else {
guard !isEmpty else {
Line 2,547: Line 2,547:
}
}


print("gHHH5YY++///\\".splitOnChanges().joined(separator: ", "))</lang>
print("gHHH5YY++///\\".splitOnChanges().joined(separator: ", "))</syntaxhighlight>


{{out}}
{{out}}
Line 2,554: Line 2,554:


=={{header|Tailspin}}==
=={{header|Tailspin}}==
<lang tailspin>
<syntaxhighlight lang="tailspin">
composer splitEquals
composer splitEquals
<reps> <nextReps>*
<reps> <nextReps>*
Line 2,562: Line 2,562:


'gHHH5YY++///\' -> splitEquals -> !OUT::write
'gHHH5YY++///\' -> splitEquals -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>g, HHH, 5, YY, ++, ///, \</pre>
<pre>g, HHH, 5, YY, ++, ///, \</pre>
Line 2,568: Line 2,568:
=={{header|tbas}}==
=={{header|tbas}}==
{{Trans|BBC BASIC}}
{{Trans|BBC BASIC}}
<lang basic>SUB SPLITUNIQUE$(s$)
<syntaxhighlight lang="basic">SUB SPLITUNIQUE$(s$)
DIM c$, d$, split$, i%
DIM c$, d$, split$, i%
c$ = LEFT$(s$, 1)
c$ = LEFT$(s$, 1)
Line 2,584: Line 2,584:


PRINT SPLITUNIQUE$("gHHH5YY++///\")
PRINT SPLITUNIQUE$("gHHH5YY++///\")
END</lang>
END</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
This is most concise with regular expressions. Note well the two steps: it could be achieved in one very clever regexp, but being that clever is usually a bad idea (for both readability and performance, in this case).
This is most concise with regular expressions. Note well the two steps: it could be achieved in one very clever regexp, but being that clever is usually a bad idea (for both readability and performance, in this case).


<lang Tcl>set string "gHHH5YY++///\\"
<syntaxhighlight lang="tcl">set string "gHHH5YY++///\\"


regsub -all {(.)\1*} $string {\0, } string
regsub -all {(.)\1*} $string {\0, } string
regsub {, $} $string {} string
regsub {, $} $string {} string
puts $string</lang>
puts $string</syntaxhighlight>


{{out}}
{{out}}
Line 2,601: Line 2,601:
=={{header|VBA}}==
=={{header|VBA}}==


<syntaxhighlight lang="vb">
<lang vb>
Option Explicit
Option Explicit


Line 2,635: Line 2,635:
Split_Special = R
Split_Special = R
End Function
End Function
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>g, HHH, 5, YY, ++, ///, \</pre>
<pre>g, HHH, 5, YY, ++, ///, \</pre>


=={{header|Wren}}==
=={{header|Wren}}==
<lang ecmascript>var split = Fn.new { |s|
<syntaxhighlight lang="ecmascript">var split = Fn.new { |s|
if (s.count == 0) return ""
if (s.count == 0) return ""
var res = []
var res = []
Line 2,659: Line 2,659:


var s = "gHHH5YY++///\\"
var s = "gHHH5YY++///\\"
System.print(split.call(s))</lang>
System.print(split.call(s))</syntaxhighlight>


{{out}}
{{out}}
Line 2,667: Line 2,667:


=={{header|XLISP}}==
=={{header|XLISP}}==
<lang lisp>(defun delimit (s)
<syntaxhighlight lang="lisp">(defun delimit (s)
(defun delim (old-list new-list current-char)
(defun delim (old-list new-list current-char)
(if (null old-list)
(if (null old-list)
Line 2,678: Line 2,678:
(list->string (delim (string->list s) '() (car (string->list s)))) )
(list->string (delim (string->list s) '() (car (string->list s)))) )


(display (delimit "gHHH5YY++///\\")) ;; NB. The "\" character needs to be escaped</lang>
(display (delimit "gHHH5YY++///\\")) ;; NB. The "\" character needs to be escaped</syntaxhighlight>
{{out}}
{{out}}
<pre>g, HHH, 5, YY, ++, ///, \</pre>
<pre>g, HHH, 5, YY, ++, ///, \</pre>


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>string 0; \change to zero-terminated convention
<syntaxhighlight lang="xpl0">string 0; \change to zero-terminated convention
char S;
char S;
[S:= "gHHH5YY++///\";
[S:= "gHHH5YY++///\";
Line 2,691: Line 2,691:
S:= S+1;
S:= S+1;
];
];
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 2,699: Line 2,699:


=={{header|Yabasic}}==
=={{header|Yabasic}}==
<lang freebasic>sub esplit$(instring$)
<syntaxhighlight lang="freebasic">sub esplit$(instring$)
if len(instring$) < 2 return instring$
if len(instring$) < 2 return instring$
ret$ = left$(instring$,1)
ret$ = left$(instring$,1)
Line 2,709: Line 2,709:
end sub
end sub


print esplit$("gHHH5YY++///\\")</lang>
print esplit$("gHHH5YY++///\\")</syntaxhighlight>


=={{header|Z80 Assembly}}==
=={{header|Z80 Assembly}}==
<lang z80>PrintChar equ &BB5A ;Amstrad CPC BIOS call
<syntaxhighlight lang="z80">PrintChar equ &BB5A ;Amstrad CPC BIOS call
Terminator equ 0 ;marks the end of a string
Terminator equ 0 ;marks the end of a string
org &8000
org &8000
Line 2,754: Line 2,754:


StringA:
StringA:
byte "gHHH5YY++///\",0</lang>
byte "gHHH5YY++///\",0</syntaxhighlight>


{{out}}
{{out}}
Line 2,762: Line 2,762:


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>fcn group(str){
<syntaxhighlight lang="zkl">fcn group(str){
C,out := str[0],Sink(C);
C,out := str[0],Sink(C);
foreach c in (str[1,*]){ out.write(if(c==C) c else String(", ",C=c)) }
foreach c in (str[1,*]){ out.write(if(c==C) c else String(", ",C=c)) }
out.close();
out.close();
}
}
group("gHHH5YY++///\\").println();</lang>
group("gHHH5YY++///\\").println();</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,774: Line 2,774:


=={{header|ZX Spectrum Basic}}==
=={{header|ZX Spectrum Basic}}==
<lang basic> 10 LET s$="gHHH5YY++///\"
<syntaxhighlight lang="basic"> 10 LET s$="gHHH5YY++///\"
20 LET c$=s$(1)
20 LET c$=s$(1)
30 LET n$=c$
30 LET n$=c$
Line 2,782: Line 2,782:
70 LET c$=s$(i)
70 LET c$=s$(i)
80 NEXT i
80 NEXT i
90 PRINT n$</lang>
90 PRINT n$</syntaxhighlight>
{{out}}
{{out}}
<pre>g, HHH, 5, YY, ++, ///, \</pre>
<pre>g, HHH, 5, YY, ++, ///, \</pre>