简体   繁体   中英

How to capitalize every other letter in a string/array in Swift?

I am trying to capitalize every even numbered placeholder in a string in Swift. So the character in [0],[2],[4],[6] all get uppercased.

I have a declared variable:

var str = "This is a test" 

I have an array that explodes the variable into an array:

let characters = Array(str) //Creates the array "["T", "h", "i", "s", " ", "i", "s", " ", "a", " ", "t", "e", "s", "t"]\n"

On top of that, I am creating an empty array to input the newly capitalized/lowercased letters

var newCharacters = Array<Character>()

And then declaring index at 0

var index = 0 //declaring the index at 0

I am trying to figure out how to create the for loop that will sniff out the even numbered array item and then capitalize the character found in it.

I have created a for loop that will manipulate the even numbered placeholders in the array, I just do not know the syntax to capitalize the string of every other one:

for letter in characters {

   if index % 2 == 0 {

     }

}

I am trying to figure out: what the syntax is to capitalize every other letter (even numbers in the array), put them in the new array, and then convert it back to a string.

The end result should be:

"ThIs iS TeSt"

One way is using stride :

var str = "This is a test" 
var chars = Array(str).map { String($0) }
for i in stride(from: 0, to: chars.count, by: 2) {
  chars[i] = chars[i].uppercased()
}
var hiphopcasedStr = chars.joined()

Note that while you're in Unicode land, some characters uppercase to multicharacter strings, so array of Character is not quite appropriate (thus the conversion to array of String ).

You can combine enumerated , map , and joined in sequence to create the result:

let str = "This is a test"

let result = str.enumerated()
                .map { $0.offset % 2 == 0 ? String($0.element).uppercased() : String($0.element) }
                .joined()

print(result)
 ThIs iS A TeSt 

Explanation:

  1. A String can be enumerated as if it were an array of Character . Calling .enumerated() on a String causes it to produces a sequence of (offset: Int, element: Character) tuples.
  2. map takes a sequence and creates an array. The closure following map is called for each element of the sequence in turn and the value that the closure returns becomes the next element in the new array.
  3. $0 is the default name for the value passed to map. In this case, we're passing the (offset: Int, element: Character) tuple. $0.offset is the position of the character in the String , and $0.element is the character.
  4. The ternary operator is used here to return the uppercased() String that is created from the Character if the offset is even or just the String if the offset is odd.
  5. The result of the map is [String] , and joined() is then used to join the array of String back into a single String .
let str = "This is a test"
let result = str.indices.map {
                 str.distance(from: str.startIndex, to: $0) % 2 == 0 ?
                 str[$0...$0].uppercased() :
                 str[$0...$0].lowercased() }.joined()
print(result)   // "ThIs iS A TeSt\n"

or as a mutating method on StringProtocol:

extension StringProtocol where Self: RangeReplaceableCollection {
    mutating func capitalizeEveryOther() {
        indices.forEach {
            replaceSubrange($0...$0, with:
                distance(from: startIndex, to: $0) % 2 == 0 ?
                self[$0...$0].uppercased() :
                self[$0...$0].lowercased() )
        }
    }
    var capitalizingEveryOther: Self {
        var result = self
        result.capitalizeEveryOther()
        return result
    }
}

var str5 = "This is a test"

str5.capitalizeEveryOther()

print(str5)     // ThIs iS A TeSt

try this code

var str = "This is a test"
var result = [String]()
for (index,element) in str.enumerated() {
    var val:String =  String(element).lowercased()
    if index % 2 == 0 {
        val = String(element).uppercased()
    }
    result.append(val)
}

print(result.joined())

result

ThIs iS A TeSt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM