Swift 程式查詢字串中最長的單詞
在 Swift 中,字串是一系列字元。因此,字串可以包含小單詞和大單詞。因此,使用以下方法,我們可以找到字串中最大的單詞。
使用 component() 方法
使用使用者定義的方法
示例
Input String: "Rabbit run fast" Output String: "Rabbit"
這裡,字串中所有給定單詞中最大的單詞是“Rabbit”。
方法 1:使用 component() 方法
components() 方法用於根據給定分隔符從給定字串建立子字串陣列。因此,這裡我們使用 components(separatedBy:.whitespaces) 方法,並使用 .wihitespaces 作為引數來建立一個子字串陣列,其中子字串由空格字元分隔。然後,我們將陣列元素的長度相互比較以找到最長的單詞。
語法
str.components(separatedBy:.whitespaces)
這裡,component() 方法在 str 字串上呼叫,並返回一個由空格分隔的子字串陣列。
演算法
步驟 1 − 建立一個函式,該函式以輸入字串作為引數並返回最長的單詞。
步驟 2 − 在函式內部,我們透過使用 component() 函式將字串劃分為子字串來建立子字串陣列。其中子字串由空格字元分隔。
步驟 3 − 建立一個空字串來儲存結果。
步驟 4 − 執行一個 for-in 迴圈來迭代每個子字串。並將每個子字串的長度與當前子字串進行比較。
步驟 5 − 如果當前子字串長度是最長長度,則將此子字串新增到結果字串中。
步驟 6 − 返回結果字串。
步驟 7 − 建立一個字串。
步驟 8 − 呼叫函式並將字串作為引數傳遞給它
步驟 9 − 顯示輸出。
示例
import Foundation import Glibc // Function to find the longest word in the given string func longestWord(str: String) -> String { let wordArray = str.components(separatedBy: .whitespacesAndNewlines) var longWord = "" for w in wordArray { if w.count > longWord.count { longWord = w } } return longWord } // Input string let myString = "Swift support String" let resWord = longestWord(str: myString) print("Longest word in the \"\(myString)\" is:\(resWord)")
輸出
Longest word in the "Swift support String" is: support
方法 2:使用使用者定義函式
我們可以使用使用者定義的函式在字串中找到最長的單詞。這裡我們建立一個函式,它接收輸入字串並返回字串中存在的最長單詞。
演算法
步驟 1 − 建立一個函式,該函式以輸入字串作為引數並返回最長的單詞。
步驟 2 − 在函式內部,我們建立兩個變數來儲存迭代每個單詞時的當前單詞以及跟蹤最長單詞。
步驟 3 − 執行一個 for-in 迴圈來迭代每個子字串。
步驟 4 − 檢查當前字元是否為空格或換行符,因為它表示單詞的結尾。
步驟 5: − 在這種情況下,我們將當前單詞的長度與最長單詞進行比較。
步驟 6 − 將最長單詞儲存在變數中
步驟 7 − 再次重新檢查以確保該單詞是最長單詞。
步驟 8 − 返回結果單詞。
步驟 9 − 建立一個字串。
步驟 10 − 呼叫函式並將字串作為引數傳遞給它
步驟 11 − 顯示輸出。
示例
在以下 Swift 程式中,我們將找到字串中最長的單詞。為此,我們將定義一個函式,該函式以字串作為輸入。此函式在 for-in 迴圈的幫助下迭代字串的每個字元,並檢查字元是否為空格或換行符,因為它表示單詞的結尾。在這種情況下,我們將 currentWord 和 longestWord 的長度進行比較,並在必要時更新 longestWord。然後我們將 currentWord 重置為空。如果字元不是空格或換行符,則將其附加到 currentWord 以生成當前單詞。在所有之後,我們再次重新檢查以確認結果單詞是最長單詞。最後返回最長單詞。
import Foundation import Glibc func getLongestWord(str: String) -> String { var longestWord = "" var currentWord = "" for c in str { if c.isWhitespace || c.isNewline { if currentWord.count > longestWord.count { longestWord = currentWord } currentWord = "" } else { currentWord.append(c) } } if currentWord.count > longestWord.count { longestWord = currentWord } return longestWord } let myString = "Rohan lover Swift programming" let resWord = getLongestWord(str:myString) print("The longest word from the \" \(myString)\":\(resWord)")
輸出
The longest word from the " Rohan lover Swift programming": programming
結論
因此,這就是我們在字串中查詢最長單詞的方法。查詢最長單詞對於文字分析、資料處理、遊戲開發、使用者輸入驗證、語言學習等很有用。您也可以根據需要使用最長單詞。這裡兩種方法都返回準確的結果。