How to resolve the algorithm Split a character string based on change of character step by step in the Swift programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Split a character string based on change of character step by step in the Swift programming language

Table of Contents

Problem Statement

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: should be split and show:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Split a character string based on change of character step by step in the Swift programming language

Source code in the swift programming language

public extension String {
  func splitOnChanges() -> [String] {
    guard !isEmpty else {
      return []
    }

    var res = [String]()
    var workingChar = first!
    var workingStr = "\(workingChar)"

    for char in dropFirst() {
      if char != workingChar {
        res.append(workingStr)
        workingStr = "\(char)"
        workingChar = char
      } else {
        workingStr += String(char)
      }
    }

    res.append(workingStr)

    return res
  }
}

print("gHHH5YY++///\\".splitOnChanges().joined(separator: ", "))


  

You may also check:How to resolve the algorithm Text processing/Max licenses in use step by step in the Scala programming language
You may also check:How to resolve the algorithm Anonymous recursion step by step in the APL programming language
You may also check:How to resolve the algorithm Factorial primes step by step in the Lua programming language
You may also check:How to resolve the algorithm Rosetta Code/Fix code tags step by step in the PicoLisp programming language
You may also check:How to resolve the algorithm Get system command output step by step in the Ursa programming language