Swift:如何在某个角色之前获取字符串?

时间:2015-04-02 20:18:40

标签: ios swift

如何在swift中的某个字符前获取字符串?下面的代码是我在Objective C中的做法,但似乎无法在Swift中执行相同的任务。有关如何实现这一目标的任何提示或建议? rangeOfString似乎根本不起作用(尽管斯威夫特一直在为我做好准备)。

NSRange range = [time rangeOfString:@" "];
NSString *startDate =
[time substringToIndex:range.location];

从上面的代码中我可以看到,我能够在Objective C中的空格字符之前获取字符串。

编辑:如果我尝试这样的话

 var string = "hello Swift"
 var range : NSRange = string.rangeOfString("Swift")

我收到以下错误。

  

无法转换表达式' NSString'输入'(String,   options:NSStringCompareOptions,range:Range?,locale:   ?NSLocale)'

不确定我做错了什么或如何正确解决。

11 个答案:

答案 0 :(得分:86)

使用componentsSeparatedByString(),如下所示:

var delimiter = " "
var newstr = "token0 token1 token2 token3"
var token = newstr.components(separatedBy: delimiter)
print (token[0])

或者使用您的具体案例:

var delimiter = " token1"
var newstr = "token0 token1 token2 token3"
var token = newstr.components(separatedBy: delimiter)
print (token[0])

答案 1 :(得分:22)

您可以使用rangeOfString()

提供的String执行相同操作
let string = "Hello Swift"
if let range = string.rangeOfString("Swift") {
   let firstPart = string[string.startIndex..<range.startIndex]
   print(firstPart) // print Hello
}

您也可以使用您的方法substringToIndex()

来实现它
let string = "Hello Swift"
if let range = string.rangeOfString("Swift") {
   firstPart = string.substringToIndex(range.startIndex)
   print(firstPart) // print Hello
}

Swift 3更新:

let string = "Hello Swift"
if let range = string.range(of: "Swift") {
    let firstPart = string[string.startIndex..<range.lowerBound]
    print(firstPart) // print Hello
}

希望这可以帮到你;)

答案 2 :(得分:7)

跟进Syed Tariq的回答:如果你只想在分隔符之前使用字符串(否则,你会收到一个数组[String]):

var token = newstr.components(separatedBy: delimiter).first

答案 3 :(得分:3)

如果您想要一个不涉及基础的解决方案,您可以使用find并切片:

let str = "Hello, I must be going."

if let comma = find(str, ",") {
    let substr = str[str.startIndex..<comma]
    // substr will be "Hello"
}

如果在没有找到这样的字符的情况下明确想要一个空字符串,你可以使用nil-coalescing运算符:

let str = "no comma"
let comma = find(str, ",") ?? str.startIndex
let substr = str[str.startIndex..<comma]  // substr will be ""

注意,与componentsSeparatedByString技术不同,这不需要创建数组,只需要扫描到第一次出现的字符,而不是将整个字符串分解为字符分隔的数组。

答案 4 :(得分:3)

我的2美分:-)使用Swift 3.0,类似于PHP strstr

extension String {

    func strstr(needle: String, beforeNeedle: Bool = false) -> String? {
        guard let range = self.range(of: needle) else { return nil }

        if beforeNeedle {
            return self.substring(to: range.lowerBound)
        }

        return self.substring(from: range.upperBound)
    }

}

<强> Usage1

"Hello, World!".strstr(needle: ",", beforeNeedle: true) // returns Hello

<强> Usage2

"Hello, World!".strstr(needle: " ") // returns World!

答案 5 :(得分:2)

要将String变为部分,直到第一次出现指定的String,你可以像这样扩展String:

extension String {

    mutating func until(_ string: String) {
        var components = self.components(separatedBy: string)
        self = components[0]
    }

}

这可以这样调用:

var foo = "Hello Swift"
foo.until(" Swift") // foo is now "Hello"

答案 6 :(得分:2)

迅速添加5个扩展名

extension String {
    func stringBefore(_ delimiter: Character) -> String {
        if let index = firstIndex(of: delimiter) {
            return String(prefix(upTo: index))
        } else {
            return ""
        }
    }
    
    func stringAfter(_ delimiter: Character) -> String {
        if let index = firstIndex(of: delimiter) {
            return String(suffix(from: index).dropFirst())
        } else {
            return ""
        }
    }
}

let str = "n1:lolz"
print(str.stringBefore(":")) // n1
print(str.stringAfter(":")) // lolz

let str = "n1:"
print(str.stringBefore(":")) // n1
print(str.stringAfter(":")) // empty string

let str = "n1+lolz"
print(str.stringBefore(":")) // empty string
print(str.stringAfter(":")) // empty string

这应该根据您的需求和边缘情况进行微调。

答案 7 :(得分:1)

您可以使用rangeOfString,但它会返回Range<String.Index>类型,而不是NSRange

let string = "hello Swift"
if let range = string.rangeOfString("Swift") {
    print(string.substringToIndex(range.startIndex))
}

答案 8 :(得分:1)

SelectMany

输出为:Hello

答案 9 :(得分:1)

以下是一种整体组合

let string = "This a string split using * and this is left."
if let range = string.range(of: "*") {
    let lastPartIncludingDelimiter = string.substring(from: range.lowerBound)
    print(lastPartIncludingDelimiter) // print * and this is left.

    let lastPartExcludingDelimiter = string.substring(from: range.upperBound)
    print(lastPartExcludingDelimiter) // print and this is left.

    let firstPartIncludingDelimiter = string.substring(to: range.upperBound)
    print(firstPartIncludingDelimiter) // print This a string split using *

    let firstPartExcludingDelimiter = string.substring(to: range.lowerBound)
    print(firstPartExcludingDelimiter) // print This a string split using
}

答案 10 :(得分:1)

您可以在 Swift 4或更高版本

中使用方法prefix(upTo:)
var string = "hello Swift"
if let index = string.firstIndex(of: " ") {
    let firstPart = string.prefix(upTo: index)
    print(firstPart) // print hello
}