Swift程式:檢查字串是否以指定子字串開頭
Swift 提供了一個 `hasPrefix()` 函式來檢查字串是否以指定的子字串開頭。`hasPrefix()` 函式返回一個布林值,指示指定的子字串是否與輸入字串的起始字串字元匹配。`hasPrefix()` 函式區分大小寫,這意味著根據此函式,“a”和“A”是兩個不同的值。
輸入
String = “Ram got first place” SubString = “Ram”
輸出
Yes
這裡,子字串的字元與輸入字串的起始字元匹配。
語法
func hasPrefix(value)
這裡,`value` 表示一個字串。如果 `value` 與輸入字串的起始字元匹配,則此函式返回 `true`。否則,它將返回 `false`。如果 `value` 是空字串,它也返回 `false`。
演算法
步驟 1 - 建立一個字串。
步驟 2 - 建立一個子字串。
步驟 3 - 使用 `hasPrefix()` 函式確定給定字串是否以指定的子字串開頭。
步驟 4 - 列印輸出。
示例 1
在下面的 Swift 程式中,我們將檢查字串是否以給定的子字串開頭。因此,建立一個字串和兩個子字串。然後使用 `hasPrefix()` 函式檢查指定的字串是否以子字串開頭。如果字串以子字串開頭,則列印“true”。否則,列印“false”。
import Foundation
import Glibc
let myStr = "Ram likes to teach Swift programming language"
let prefixStr1 = "Ram"
let prefixStr2 = "Suman"
// Checking if the string begins with the
// specified substring or not
var res1 = myStr.hasPrefix(prefixStr1)
var res2 = myStr.hasPrefix(prefixStr2)
print("Is '\(myStr)' starts with '\(prefixStr1)' substring?:", res1)
print("Is '\(myStr)' starts with '\(prefixStr2)' substring?:", res2)
輸出
Is 'Ram likes to teach Swift programming language' starts with 'Ram' substring?: true Is 'Ram likes to teach Swift programming language' starts with 'Suman' substring?: false
示例 2
在下面的 Swift 程式中,我們將檢查字串是否以給定的子字串開頭。因此,建立一個字串和一個子字串。然後使用 `hasPrefix()` 函式確定指定的字串是否以子字串開頭。如果輸入字串以子字串開頭,則列印“YES! 給定字串以指定的子字串開頭。”。否則,列印“NO! 給定字串不是以指定的子字串開頭。”
import Foundation
import Glibc
let myStr = "Learn Swift programming"
let prefixStr = "Learn"
// Determine if the string begins with the
// specified prefix substring or not
if myStr.hasPrefix(prefixStr) {
print("YES! the given string starts with the specified substring.")
} else {
print("NO! the given string does not starts with the specified substring.")
}
輸出
YES! the given string starts with the specified substring.
結論
這就是我們如何使用 `hasPrefix()` 函式檢查字串是否以指定的子字串開頭。此方法將子字串的每個字元與輸入字串的起始字元進行比較。如果任何字元與給定字串不匹配,則它將返回 `false`。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP