let range = str.range(of: "World")
if let range = range {
let startIndex = str.distance(from: str.startIndex, to: range.lowerBound)
l"> let range = str.range(of: "World")
if let range = range {
let startIndex = str.distance(from: str.startIndex, to: range.lowerBound)
l">
117.info
人生若只如初见

在Swift 3.0中使用String.range

在Swift 3.0中,你可以使用String.range来获取子字符串在原始字符串中的位置。这里是一个简单的示例:

let str = "Hello, World!"
let range = str.range(of: "World")
if let range = range {
let startIndex = str.distance(from: str.startIndex, to: range.lowerBound)
let endIndex = str.distance(from: str.startIndex, to: range.upperBound)
print("Found at index \(startIndex) to \(endIndex)")
} else {
print("Not found")
}

输出结果将是 “Found at index 7 to 12”,表示子字符串 “World” 在原始字符串中的位置范围。

未经允许不得转载 » 本文链接:https://www.117.info/ask/fede3AzsLBAFVBFw.html

推荐文章

  • Swift:使用 scheduleTimerWithTimeInterval 调用的额外参数

    在Swift中,可以使用scheduleTimerWithTimeInterval方法调用定时器,并传递额外的参数。这可以通过使用闭包来实现。
    下面是一个示例,演示如何在定时器中传...

  • Swift iOS doRelativeDate格式具有不同的值,除了“今天”

    Swift iOS doRelativeDate格式具有以下不同的值,除了"今天": “昨天” - 表示相对于当前日期的前一天。 “明天” - 表示相对于当前日期的后一天。 “前天” - ...

  • Swift版本的componentsSeparatedByString

    在Swift中,可以使用components(separatedBy:)方法来分割字符串。这个方法接受一个分隔符作为参数,并返回一个包含拆分后的子字符串的数组。
    下面是一个示例...

  • swift字符串替换怎么实现

    在Swift中,可以使用replacingOccurrences(of:with:)方法来实现字符串的替换。该方法接受两个参数,第一个参数为要替换的子字符串,第二个参数为替换后的字符串。...

  • SuspendThread WOW64在内核代码中挂起

    在内核代码中,可以使用SuspendThread WOW64函数来挂起一个线程。该函数的原型如下:
    DWORD WINAPI SuspendThread(
    HANDLE hThread
    ); 参数hThre...

  • php.ini中没有让我disable_functions选项

    确实,php.ini文件中没有默认提供disable_functions选项。
    如果你想禁用特定的函数,可以通过在php.ini文件中手动添加disable_functions = 函数名1, 函数名...

  • Linux内核模块中的module_init和init_module有什么区别

    module_init和init_module都是Linux内核模块中用来初始化模块的函数,但是它们的用法和执行顺序有所不同。 module_init:module_init是一个宏,在模块代码中使用...

  • 使用EnterCriticalSection时出现问题

    使用EnterCriticalSection时可能出现以下问题: 死锁:如果多个线程在不同的顺序尝试进入临界区,则可能导致死锁。例如,线程A先进入临界区1然后尝试进入临界区2...