Remove nth character from string

I have seen many methods for removing the last character from a string. Is there a way to remove any old character based on its index?

+6
source share
2 answers

While row indexes are not random access and are not numbers, you can increase their number to access the nth character:

var s = "Hello, I must be going" s.removeAtIndex(advance(s.startIndex, 5)) println(s) // prints "Hello I must be going" 

Of course, you should always check that the string is at least 5 long before doing this!

edit: as @MartinR points out, you can use the forward-index option to advance to avoid the risk of getting past the end:

 let index = advance(s.startIndex, 5, s.endIndex) if index != s.endIndex { s.removeAtIndex(index) } 

As always, options are your friend:

 // find returns index of first match, // as an optional with nil for no match if let idx = s.characters.index(of:",") { // this will only be executed if non-nil, // idx will be the unwrapped result of find s.removeAtIndex(idx) } 
+10
source

var hello = "hello world!"

Say we want to remove the "w". (He is in the sixth position of the index.)

First: create an index for this position. (I am making the return type explicit, not required).

let index:Index = hello.startIndex.advancedBy(6)

Second: call removeAtIndex () and pass it our newly made index. (Note that it returns the corresponding character)

let choppedChar:Character = hello.removeAtIndex(index)

print(hello) // print hello orld!

print(choppedChar) // prints w

0
source

Source: https://habr.com/ru/post/981716/


All Articles