Home > OS >  Check every single word of String – Swift
Check every single word of String – Swift

Time:07-09

I want to check every single word of a string for a certain character, and if that word has the certain character then this word does a certain thing and once there is a space bar after that certain word, then do another thing ...

let sentence = "Hello, World"
let certainCharacter = "e"

if word has certaincharacter {
    print("this word has the character") 
} else {
    print("this word does not have the character")
}

I have tried with .contains but that always checks the entire sentence, not word for word. How can I do so?

CodePudding user response:

split returns an Array with seperator.

filter will return array of words that contains your character.

Try This:

 let sentence = "Hello, World I am back with Love"
        let chars = sentence.split(separator:  " ")
        let filtered = chars.filter {
            $0.contains("e")
        }
        print(filtered)
// prints: ["Hello,", "Love"]

CodePudding user response:

import Foundation

let sentence = "Hello, World"
let arr = sentence.components(separatedBy: " ")

// creates Array: arr=["Hello,", "World"]

arr.forEach{word in
if word.contains("e"){print(word)
}else{print("whatever")} }

CodePudding user response:

try this Simple logic...

import Foundation import UIKit

let sentence = "Hello, World"

let certainCharacter = "e"

if sentence.description.contains(certainCharacter){

print("this word has the character")

}else{

print("this word does not have the character")

}

CodePudding user response:

let sentence = "Hello, World"
let char: Character = "e"

if sentence.contains(char) {
    print("this word has the character") 
} else {
    print("this word does not have the character")
}
  • Related