2

I need to check if the index number of a string is divisible by 2.

Here is what I need to do:

I have a string 0BCB7A0D87AD101B500B I need to remove all "0" characters from the string, but only if they are at an odd number in the string. I need to break it down as follows

0B|CB|7A|0D|87|AD|10|1B|50|0B

and only remove the "0" if it is the first character in the pair.

B|CB|7A|D|87|AD|10|1B|50|B

Then put the string back together

BCB7AD87AD101B50B

This code doesn't work, but this is how I am looking at doing it. I'm breaking up the string into an array:

   var characters = Array("0BCB7A0D87AD101B500B")

    for letter in characters {
        if characters(index: Int) % 2 != 0 { // if index has a remainder after being divided by 2
           if letter == "0"{ 
           characters.removeAtIndex(index: Int)
            }
        }

    }

I just can't divide or get the index number of the letter/string in the array.

3 Answers 3

2

This would work, it uses a separate variable (index) to keep track of the index:

var characters = Array("0BCB7A0D87AD101B500B")
var newCharacters = Array<Character>()
var index = 0
for letter in characters {
    if index % 2 == 1 || letter != "0" {
        newCharacters.append(letter)
    }
    index++
}
var newString = String(newCharacters)

Sign up to request clarification or add additional context in comments.

2 Comments

Hmmm, this produces BCB7AD87AD181B53B349E51E9688B0000000. It has removed all the 0s.
I think you are using another input string, then.
1

A functional approach to the problem

// zip each character with the index (enumerate)
let charsWithIndex = enumerate("0BCB7A0D87AD101B500B")
// filter away the unwanted characters (filter) and get rid of the indexes (map)
let filteredCharacters = filter(charsWithIndex) { index, char in !(char == "0" && index % 2 == 0) }.map { String($0.1) }
// put the string back together (join)
let filteredString = "".join(filteredCharacters)

Comments

0

Thank ou for your code. I was able to adjust it to remove at the right points.

var characters = Array("0BCB7A0D87AD101B500B")

    var newCharacters = Array<Character>()
    var index = 1
    for letter in characters {
        if index % 2 == 0 {
            newCharacters.append(letter)
        }
        if index % 2 != 0 && letter != "0" {
            newCharacters.append(letter)
        }
        index++
    }
    var newString = String(newCharacters)

1 Comment

That's exactly what my code is doing, though. There should be no difference. I let index begin at 0, because string positions start with 0. And you have split the if statement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.