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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29421726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 05:28:35  来源:igfitidea点击:

Swift : How to get the string before a certain character?

iosswift

提问by Danger Veger

How do I get the string before a certain character in swift? The code below is how I did it in Objective C, but can't seem to perform the same task in Swift. Any tips or suggestions on how to achieve this? rangeOfStringseems to not work at all in swift (although Swift has been acting up for me again).

如何快速获取某个字符之前的字符串?下面的代码是我在 Objective C 中的做法,但似乎无法在 Swift 中执行相同的任务。关于如何实现这一目标的任何提示或建议?rangeOfString似乎在 swift 中根本不起作用(尽管 Swift 再次为我行事)。

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

As you can see from the code above I am able to get the string before the space character in Objective C.

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

Edit : If I try something like this

编辑:如果我尝试这样的事情

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

I get the following error.

我收到以下错误。

Cannot convert the expression's type 'NSString' to type '(String, options: NSStringCompareOptions, range: Range?, locale: NSLocale?)'

无法将表达式的类型“NSString”转换为“(String, options: NSStringCompareOptions, range: Range?, locale: NSLocale?)”

Not sure what I did wrong exactly or how to resolve it correctly.

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

回答by Syed Tariq

Use componentsSeparatedByString() as shown below:

使用 componentsSeparatedByString() 如下所示:

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

Or to use your specific case:

或者使用您的特定案例:

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

回答by Kevin Machado

You can do the same with rangeOfString()provided by Stringclass

你可以用rangeOfString()提供的String类做同样的事情

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

You can alsoachieve it with your method substringToIndex()

你也可以用你的方法实现它substringToIndex()

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

Swift 3 UPDATE:

斯威夫特 3 更新:

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

Hope this can help you ;)

希望这可以帮到你 ;)

回答by Tim Newton

Following up on Syed Tariq's answer: If you only want the string before the delimiter (otherwise, you receive an array [String]):

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

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

回答by AamirR

My 2 cents :-) using Swift 3.0, similar to PHP strstr

我的 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

用法1

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

Usage2

用法2

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

回答by Michael Wang

You could use the method prefix(upTo:)in Swift 4 or above

您可以在Swift 4 或更高版本中使用方法prefix(upTo:)

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

回答by Airspeed Velocity

If you want a solution that doesn't involve pulling in foundation, you can do it with findand slicing:

如果你想要一个不涉及基础的解决方案,你可以用find切片来实现:

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

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

If you explicitly want an empty string in the case where no such character is found, you can use the nil-coalescing operator:

如果在找不到此类字符的情况下明确想要一个空字符串,则可以使用 nil-coalescing 运算符:

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

Note, unlike the componentsSeparatedByStringtechnique, this does not require the creation of an array, and only requires scanning up to the first occurrence of the character rather than breaking the entire string up into the character-delimited array.

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

回答by Benno Kress

To mutate a String into the part until the first appearance of a specified String you could extend String like this:

要将 String 变异到部件中,直到第一次出现指定的 String,您可以像这样扩展 String:

extension String {

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

}

This can be called like this then:

这可以这样调用:

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

回答by Sai kumar Reddy

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

Output is: Hello

输出是:你好

回答by anoop4real

Below is kind of a whole combo

下面是一个完整的组合

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
}

回答by Rob

You can use rangeOfString, but it returns a Range<String.Index>type, not a NSRange:

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

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