Split a character string based on change of character

From Rosetta Code
Revision as of 10:48, 25 February 2017 by rosettacode>Spamfortress (Added C++ Implementation)
Task
Split a character string based on change of character
You are encouraged to solve this task according to the task description, using any language you may know.


Task

Split a (character) string into comma (plus a blank) delimited strings based on a change of character   (left to right).

Show the output here   (use the 1st example below).


Blanks should be treated as any other character   (except they are problematic to display clearly).   The same applies to commas.


For instance, the string:

 gHHH5YY++///\ 

should be split and show:

 g, HHH, 5, YY, ++, ///, \ 



ALGOL 68

Works with: ALGOL 68G version Any - tested with release 2.8.3.win32

<lang algol68>BEGIN

   # returns s with ", " added between each change of character #
   PROC split on characters = ( STRING s )STRING:
        IF s = "" THEN
           # empty string #
           ""
        ELSE
           # allow for 3 times as many characters as in the string #
           # this would handle a string of unique characters       #
           [ 3 * ( ( UPB s - LWB s ) + 1 ) ]CHAR result;
           INT  r pos  := LWB result;
           INT  s pos  := LWB s;
           CHAR s char := s[ LWB s ];
           FOR s pos FROM LWB s TO UPB s DO
               IF s char /= s[ s pos ] THEN
                   # change of character - insert ", " #
                   result[ r pos     ] := ",";
                   result[ r pos + 1 ] := " ";
                   r pos +:= 2;
                   s char := s[ s pos ]
               FI;
               result[ r pos ] := s[ s pos ];
               r pos +:= 1
           OD;
           # return the used portion of the result #
           result[ 1 : r pos - 1 ]
        FI ; # split on characters #
   print( ( split on characters( "gHHH5YY++///\" ), newline ) )

END</lang>

Output:
g, HHH, 5, YY, ++, ///, \

AppleScript

Translation of: JavaScript

<lang AppleScript>on run

   intercalate(", ", ¬
       map(curry(intercalate)'s lambda(""), ¬
           group("gHHH5YY++///\\")))
   
   --> "g, HHH, 5, YY, ++, ///, \\"
   

end run


-- GENERIC FUNCTIONS

-- group :: Eq a => [a] -> a on group(xs)

   script eq
       on lambda(a, b)
           a = b
       end lambda
   end script
   
   groupBy(eq, xs)

end group

-- groupBy :: (a -> a -> Bool) -> [a] -> a on groupBy(f, xs)

   set mf to mReturn(f)
   
   script enGroup
       on lambda(a, x)
           set h to cond(length of (active of a) > 0, item 1 of active of a, missing value)
           
           if h is not missing value and mf's lambda(h, x) then
               {active:(active of a) & x, sofar:sofar of a}
           else
               {active:{x}, sofar:(sofar of a) & {active of a}}
           end if
       end lambda
   end script
   
   if length of xs > 0 then
       set dct to foldl(enGroup, {active:{item 1 of xs}, sofar:{}}, tail(xs))
       sofar of dct & cond(length of (active of dct) > 0, {active of dct}, {})
   else
       {}
   end if

end groupBy

-- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs)

   tell mReturn(f)
       set v to startValue
       set lng to length of xs
       repeat with i from 1 to lng
           set v to lambda(v, item i of xs, i, xs)
       end repeat
       return v
   end tell

end foldl

-- cond :: Bool -> a -> a -> a on cond(bool, f, g)

   if bool then
       f
   else
       g
   end if

end cond

-- intercalate :: Text -> [Text] -> Text on intercalate(strText, lstText)

   set {dlm, my text item delimiters} to {my text item delimiters, strText}
   set strJoined to lstText as text
   set my text item delimiters to dlm
   return strJoined

end intercalate

-- map :: (a -> b) -> [a] -> [b] on map(f, xs)

   tell mReturn(f)
       set lng to length of xs
       set lst to {}
       repeat with i from 1 to lng
           set end of lst to lambda(item i of xs, i, xs)
       end repeat
       return lst
   end tell

end map

-- curry :: (Script|Handler) -> Script on curry(f)

   script
       on lambda(a)
           script
               on lambda(b)
                   lambda(a, b) of mReturn(f)
               end lambda
           end script
       end lambda
   end script

end curry

-- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f)

   if class of f is script then
       f
   else
       script
           property lambda : f
       end script
   end if

end mReturn

-- tail :: [a] -> [a] on tail(xs)

   if length of xs > 1 then
       items 2 thru -1 of xs
   else
       {}
   end if

end tail</lang>

Output:
g, HHH, 5, YY, ++, ///, \

BBC BASIC

<lang bbcbasic>REM >split PRINT FN_split( "gHHH5YY++///\" ) END

DEF FN_split( s$ ) LOCAL c$, d$, split$, i% c$ = LEFT$( s$, 1 ) split$ = "" FOR i% = 1 TO LEN s$

 d$ = MID$( s$, i%, 1 )
 IF d$ <> c$ THEN
   split$ += ", "
   c$ = d$
 ENDIF
 split$ += d$

NEXT = split$</lang>

Output:
g, HHH, 5, YY, ++, ///, \

C++

<lang cpp>

  1. include<string>
  2. include<iostream>

std::string spliter(std::string input) {

  bool firstCommaPast = false;
  std::string res ="";
  char prev = '\0';
  for(std::string::iterator it = input.begin(); it != input.end();++it) {
     if(*it!=prev) {
        if(!firstCommaPast) {
           firstCommaPast = true;
        } else {
           res+=",";
        }
     }
     res+=*it;
     prev=*it;
  }
  return res;

}

int main() {

  std::string input = R"(gHHH5YY++///\)";
  std::string res = spliter(input);
  std::cout<<res;

} </lang>

Output:
g,HHH,5,YY,++,///,\


Common Lisp

<lang lisp>(defun split (string)

 (flet ((make-buffer ()
          (make-array 0 :element-type 'character :adjustable t :fill-pointer t)))
   (loop with buffer = (make-buffer)
         with result
         for prev = nil then c
         for c across string
         when (and prev (char/= c prev))
           do (push buffer result)
              (setf buffer (make-buffer))
         do (vector-push-extend c buffer)
         finally (push buffer result)
                 (format t "~{~A~^, ~}"(nreverse result)))))

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

Output:
g, HHH, 5, YY, ++, ///, \

Elixir

<lang elixir>split = fn str ->

         IO.puts " input string: #{str}"
         String.graphemes(str)
         |> Enum.chunk_by(&(&1))
         |> Enum.map_join(", ", &Enum.join &1)
         |> fn s -> IO.puts "output string: #{s}" end.()
       end

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

Output:
 input string: gHHH5YY++///\
output string: g, HHH, 5, YY, ++, ///, \

Fortran

This is F77 style, except for the END SUBROUTINE SPLATTER which would be just END, which for F90 is also allowable outside of the MODULE protocol. Linking the start/stop markers by giving the same name is helpful, especially when the compiler checks for this. The $ symbol at the end of a FORMAT code sequence is a common F77 extension, meaning "do not finish the line" so that a later output will follow on. This is acceptable to F90 and is less blather than adding the term ,ADVANCE = "NO" inside a WRITE statement that would otherwise be required. Output is to I/O unit 6 which is the modern default for "standard output". The format code is A meaning "any number of characters" rather than A1 for "one character" so as to accommodate not just the single character from TEXT but also the two characters of ", " for the splitter between sequences. Alas, there is no provision to change fount or colour for this, to facilitate the reader's attempts to parse the resulting list especially when the text includes commas or spaces of its own. By contrast, with quoted strings, the standard protocol is to double contained quotes.

An alternative method would be to prepare the entire output in a CHARACTER variable then write that, but this means answering the maddening question "how long is a piece of string?" for that variable, though later Fortran has arrangements whereby a text variable is resized to suit on every assignment, as in TEMP = TEMP // more - but this means repeatedly copying the text to the new manifestation of the variable. Still another approach would be to prepare an array of fingers to each split point so that the final output would be a single WRITE using that array, and again, how big must the array be? At most, as big as the number of characters in TEXT. With F90, subroutines can declare arrays of a size determined on entry, with something like INTEGER A(LEN(TEXT))

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. Can't display the inserted commas in a different colour so as not to look like any commas in TEXT.

      CHARACTER*(*) TEXT	!The text.
      INTEGER L	!A finger.
      CHARACTER*1 C	!A state follower.
       IF (LEN(TEXT).LE.0) RETURN	!Prevent surprises in the following..
       C = TEXT(1:1)			!Syncopation: what went before.
       DO L = 1,LEN(TEXT)	!Step through the text.
         IF (C.NE.TEXT(L:L)) THEN	!A change of character?
           C = TEXT(L:L)			!Yes. This is the new normal.
           WRITE (6,1) ", "			!Set off from what went before. This is not from TEXT.
         END IF			!So much for changes.
         WRITE (6,1) C			!Roll the current character. (=TEXT(L:L))
   1     FORMAT (A,$)			!The $ sez: do not end the line.
       END DO			!On to the next character.
       WRITE (6,1)	!Thus end the line. No output item means that the $ is not reached, so the line is ended.
     END SUBROUTINE SPLATTER	!TEXT with spaces, or worse, commas, will produce an odd-looking list.
     PROGRAM POKE
     CALL SPLATTER("gHHH5YY++///\")	!The example given.
     END</lang>

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.

Output:
g, HHH, 5, YY, ++, ///, \

Go

Treating "character" as a byte: <lang go>package main

import (

   "bytes"
   "fmt"

)

func main() {

   fmt.Println(scc(`gHHH5YY++///\`))

}

func scc(s string) string {

   if len(s) < 2 {
       return s
   }
   var b bytes.Buffer
   p := s[0]
   b.WriteByte(p)
   for _, c := range []byte(s[1:]) {
       if c != p {
           b.WriteString(", ")
       }
       b.WriteByte(c)
       p = c
   }
   return b.String()

}</lang>

Output:
g, HHH, 5, YY, ++, ///, \

Haskell

<lang Haskell>import Data.List (group, intercalate)

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

Output:
g, HHH, 5, YY, ++, ///, \

Java

<lang Java>package org.rosettacode;

import java.util.ArrayList; import java.util.List;


/**

* This class provides a main method that will, for each arg provided,
* transform a String into a list of sub-strings, where each contiguous
* series of characters is made into a String, then the next, and so on,
* and then it will output them all separated by a comma and a space.
*/

public class SplitStringByCharacterChange {

   public static void main(String... args){
       for (String string : args){
           
           List<String> resultStrings = splitStringByCharacter(string);
           String output = formatList(resultStrings);
           System.out.println(output);
       }
   }
   
   /**
    * @param string String - String to split
    * @return List<\String> - substrings of contiguous characters
    */
   public static List<String> splitStringByCharacter(String string){
       
       List<String> resultStrings = new ArrayList<>();
       StringBuilder currentString = new StringBuilder();
       
       for (int pointer = 0; pointer < string.length(); pointer++){
           
           currentString.append(string.charAt(pointer));
           
           if (pointer == string.length() - 1 
                   || currentString.charAt(0) != string.charAt(pointer + 1)) {
               resultStrings.add(currentString.toString());
               currentString = new StringBuilder();
           }
       }
       
       return resultStrings;
   }
   
   /**
    * @param list List<\String> - list of strings to format as a comma+space-delimited string
    * @return String
    */
   public static String formatList(List<String> list){
       
       StringBuilder output = new StringBuilder();
       
       for (int pointer = 0; pointer < list.size(); pointer++){
           output.append(list.get(pointer));
           
           if (pointer != list.size() - 1){
               output.append(", ");
           }
       }
       
       return output.toString();
   }

}</lang>

Output:
g, HHH, 5, YY, ++, ///, \

JavaScript

ES6

Translation of: Haskell

<lang JavaScript>(() => {

   'use strict';
   // GENERIC FUNCTIONS
   // group :: Eq a => [a] -> a
   const group = xs => groupBy((a, b) => a === b, xs);
   // groupBy :: (a -> a -> Bool) -> [a] -> a
   const groupBy = (f, xs) => {
       const dct = xs.slice(1)
           .reduce((a, x) => {
               const
                   h = a.active.length > 0 ? a.active[0] : undefined,
                   blnGroup = h !== undefined && f(h, x);
               return {
                   active: blnGroup ? a.active.concat(x) : [x],
                   sofar: blnGroup ? a.sofar : a.sofar.concat([a.active])
               };
           }, {
               active: xs.length > 0 ? [xs[0]] : [],
               sofar: []
           });
       return dct.sofar.concat(dct.active.length > 0 ? [dct.active] : []);
   };
   // intercalate :: String -> [a] -> String
   const intercalate = (s, xs) => xs.join(s);
   // TEST
   return intercalate(", ", group("gHHH5YY++///\\".split())
       .map(x => x.join()));
   // -> "g, HHH, 5, YY, ++, ///, \\"

})();</lang>

Output:
g, HHH, 5, YY, ++, ///, \

Kotlin

<lang scala>// version 1.0.6

fun splitOnChange(s: String): String {

   if (s.length < 2) return s
   var t = s.take(1)  
   for (i in 1 until s.length)
       if (t.last() == s[i]) t += s[i]
       else t += ", " + s[i] 
   return t

}

fun main(args: Array<String>) {

   val s = """gHHH5YY++///\"""
   println(splitOnChange(s))

}</lang>

Output:
g, HHH, 5, YY, ++, ///, \

Lua

Note that the backslash must be quoted as a double backslash as Lua uses C-like escape sequences. <lang Lua>function charSplit (inStr)

   local outStr, nextChar = inStr:sub(1, 1)
   for pos = 2, #inStr do
       nextChar = inStr:sub(pos, pos)
       if nextChar ~= outStr:sub(#outStr, #outStr) then
           outStr = outStr .. ", "
       end
       outStr = outStr .. nextChar
   end
   return outStr

end

print(charSplit("gHHH5YY++///\\"))</lang>

Output:
g, HHH, 5, YY, ++, ///, \

Mathematica

The backslash (\) must be escaped with another backslash when defining the string. <lang Mathematica>StringCases["gHHH5YY++///\\", p : (x_) .. -> p]</lang>

Output:
{g,HHH,5,YY,++,///,\}

Perl 6

Works with: Rakudo version 2016.12

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

  1. Testing:

for Q[gHHH5YY++///\], Q[fffn⃗n⃗n⃗»»» ℵℵ☄☄☃☃̂☃☄☄] -> $string {

   put 'Original: ', $string;
   put '   Split: ', group-chars($string).join(', ');

}</lang>

Output:
Original: gHHH5YY++///\
   Split: g, HHH, 5, YY, ++, ///, \
Original: fffn⃗n⃗n⃗»»»  ℵℵ☄☄☃☃̂☃☄☄
   Split: fff, , n⃗n⃗n⃗, »»»,   , ℵℵ, ☄☄, ☃, ☃̂, ☃, ☄☄

The second test-case is to show that Perl 6 works with strings on the Unicode grapheme level, and handles combiners and zero width characters correctly. For those of you with crappy browsers, that string consists of:

  • {LATIN SMALL LETTER F} x 3
  • {ZERO WIDTH NO-BREAK SPACE} x 3
  • {LATIN SMALL LETTER N COMBINING RIGHT ARROW ABOVE} x 3
  • {RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK} x 3
  • {SPACE} x 2,
  • {ALEF SYMBOL} x 2,
  • {COMET} x 2,
  • {SNOWMAN} x 1,
  • {SNOWMAN COMBINING CIRCUMFLEX ACCENT} x 1
  • {SNOWMAN} x 1,
  • {COMET} x 2

PowerShell

Translation of: BBC BASIC

<lang PowerShell> function Split-String ([string]$String) {

   [string]$c = $String.Substring(0,1)
   [string]$splitString = $c
   for ($i = 1; $i -lt $String.Length; $i++)
   { 
       [string]$d = $String.Substring($i,1)
       if ($d -ne $c)
       {
           $splitString += ", "
           $c = $d
       }
       $splitString += $d
   }
   $splitString

} </lang> <lang PowerShell> Split-String "gHHH5YY++///\" </lang>

Output:
g, HHH, 5, YY, ++, ///, \

Python

<lang python>import itertools

try: input = raw_input except: pass

s = input() groups = [] for _, g in itertools.groupby(s):

   groups.append(.join(g))

print(' input string: %s' % s) print(' output string: %s' % ', '.join(groups))</lang>

Output:

  when using the default input

      input string:  gHHH5YY++///\
     output string:  g, HHH, 5, YY, ++, ///, \

Racket

Translation of: Python

<lang racket>#lang racket (define (split-strings-on-change s)

 (map list->string (group-by values (string->list s) char=?)))

(displayln (string-join (split-strings-on-change #<<< gHHH5YY++///\ <

                                                )
                       ", "))</lang>
Output:
g, HHH, 5, YY, ++, ///, \

REXX

<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*/ if str== | str=="," then str= 'gHHH5YY++///\' /*Not specified? Then use the default.*/ p=left(str, 1) /*placeholder for the "previous" string*/ $= /* " " " output " */

     do j=1  for length(str);      @=substr(str, j, 1)    /*obtain a char from string. */
     if @\==left(p, 1)   then do;  $=$',' @;  p=;  end    /*different then previous?   */
                         else      $=$ || @               /*a replicated character.    */
     p=p || @                                             /*append char to current list*/
     end   /*j*/

say ' input string: ' str say ' output string: ' $ /*stick a fork in it, we're all done. */</lang> output   when using the default input:

      input string:  gHHH5YY++///\
     output string:  g, HHH, 5, YY, ++, ///, \

Ruby

<lang ruby>def split(str)

 puts " input string: #{str}"
 s = str.chars.chunk(&:itself).map{|_,a| a.join}.join(", ")
 puts "output string: #{s}"
 s

end

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

Output:
 input string: gHHH5YY++///\
output string: g, HHH, 5, YY, ++, ///, \

Sidef

<lang ruby>func group(str) {

   gather {
       while (var match = (str =~ /((.)\g{-1}*)/g)) {
           take(match[0])
       }
   }

}

say group(ARGV[0] \\ 'gHHH5YY++///\\').join(', ')</lang>

Output:
g, HHH, 5, YY, ++, ///, \

Standard ML

<lang sml>(*

* Head-Tail implementation of grouping
*)

fun group' ac nil = [ac]

 | group'     nil (y::ys) = group' [y] ys
 | group' (x::ac) (y::ys) = if x=y then group' (y::x::ac) ys else (x::ac) :: group' [y] ys

fun group xs = group' nil xs

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

Output:
- groupString "gHHH5YY++///\\";
val it = "g, HHH, 5, YY, ++, ///, \\" : string

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).

<lang Tcl>set string "gHHH5YY++///\\"

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

zkl

<lang zkl>fcn group(str){

  C,out := str[0],Sink(C);
  foreach c in (str[1,*]){ out.write(if(c==C) c else String(", ",C=c)) }
  out.close();

} group("gHHH5YY++///\\").println();</lang>

Output:
g, HHH, 5, YY, ++, ///, \