how to select specific words from an string of character

时间:2018-02-03 09:54:45

标签: ios swift

I am having a line like this

#aman#ab179#167#abbash aman battra

I want output like this

  1. #aman
  2. #ab179
  3. #167
  4. #abbash

All the characters having # as first letter but I am getting the whole line instead.

This is my code

for word in stringWordsArray {
        print(word)
        if word.hasPrefix("#"){
            print("Exists")
            print(word)
        }
}

4 个答案:

答案 0 :(得分:3)

Try this Code

let str = "aman#ab179#167#abbash aman battra"
let arr = str.components(separatedBy: "#")
 for arrayString in arr{
       print("\((String (describing: arrayString).firstWord()!))")
}

// for choose first word

 extension String {
    func firstWord() -> String? {
        return self.components(separatedBy: " ").first
    }
}

答案 1 :(得分:2)

I guess, you were looking for split method of String. Here I have written example for you:

    let str = "aman#ab179#167#abbash aman battra"
    let separator = "#"
    var arr = str
        .split(separator: Character(separator)) // get array of string separated by `#`
        .map { separator + $0 }// manually add `#`
        .flatMap { $0.split(separator: " ").first } // remove substring separated by " "
    print(arr)

答案 2 :(得分:1)

This works:

let sentence = "#aman#ab179#167#abbash aman battra"
let words = sentence.split(separator: "#").flatMap { $0.split(separator: " ").first }.map { "#" + $0 }

答案 3 :(得分:0)

As per your requirement you will get exact output using below code

Swift 4.0

 let temp = "#aman#ab179#167#abbash aman battra"

 var fullNameArr = temp.components(separatedBy: .whitespaces)[0].split(separator: "#")

 var arrData = [String]()

   for word in fullNameArr {
    var temp = word
    temp.insert("#", at: temp.startIndex)
    arrData.append(String(temp))
  }
print(arrData)