ThatGuy ThatGuy - 11 days ago 6
iOS Question

Function that separates sentences and questions in swift

I want the function below to separate the sentences into an array and the questions into an array and inserting "," where the "." and "?" belong. At the moment it's printing both in the same array. Any ideas on how to fix this?

func separateAllSentences() {

// needs to print just the sentences
func separateDeclarations() { // AKA Separate sentences that end in "."
if userInput.range(of: ".") != nil { // Notice how lowercased() wasn't used
numSentencesBefore = userInput.components(separatedBy: ".") // Hasn't subtracted 1 yet
numSentencesAfter = numSentencesBefore.count - 1
separateSentencesArray = Array(numSentencesBefore)
print("# Of Sentences = \(numSentencesAfter)")
print(separateSentencesArray)
} else {
print("There are no declarations found.")
}
}

// needs to print just the questions
func separateQuestions() { // Pretty Self Explanitory
if userInput.range(of: "?") != nil {
numQuestionsBefore = userInput.components(separatedBy: "?")
numQuestionsAfter = numQuestionsBefore.count - 1
separateQuestionsArray = Array(numQuestionsBefore)
print("# Of Questions = \(numQuestionsAfter)")
print(separateQuestionsArray)
} else {
print("There are no questions found. I have nothing to solve. Please rephrase the work to solve as a question.")
}
}

// TODO: - Separate Commas
func separateCommas() {

}

separateDeclarations()
separateQuestions()
}


Console Prints Out:

Ned rode his bike 7 miles to the library.
He took a shortcut on the way home which was only 5 miles long.
How many miles did Ned ride altogether?

[# Of Sentences = 2]

["Ned rode his bike 7 miles to the library", "\nHe took a shortcut on the way home which was only 5 miles long", "\nHow many miles did Ned ride altogether?\n"]

[# Of Questions = 1]

["Ned rode his bike 7 miles to the library.\nHe took a shortcut on the way home which was only 5 miles long.\nHow many miles did Ned ride altogether", "\n"]

Ned rode his bike 7 miles to the library.
He took a shortcut on the way home which was only 5 miles long.
How many miles did Ned ride altogether?

It Should Print Out

[# Of Sentences = 2]

[# Of Questions = 1]

Sentences: ["Ned rode his bike 7 miles to the library. He took a shortcut on the way home which was only 5 miles long."]

Questions: ["How many miles did Ned ride altogether?"]

Answer
var statement = "Ned rode his bike 7 miles to the library. He took a shortcut on the way home which was only 5 miles long. How many miles did Ned ride altogether?"

var array = statement.components(separatedBy: ".")

var noOfAnswers = 0
var noOfQuestions = 0
var questions = [String]()
var answers = [String]()

for content in array {
    if content.contains("?") {
        questions.append(content)
        noOfQuestions += 1
    } else {
        answers.append(content)
        noOfAnswers += 1
    }
}

Output of playground

enter image description here

Comments