You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flutter-Dart中移除句子中的第一个单词

Swift 移除句子中第一个单词的实现方法

这里提供几种实用的实现方式,适配不同场景:

方式一:字符串分割重组

适合处理多空格、换行符等空白字符的场景,自动过滤空内容:

func removeFirstWord(from sentence: String) -> String {
    let components = sentence.components(separatedBy: .whitespacesAndNewlines)
    let nonEmptyParts = components.filter { !$0.isEmpty }
    guard nonEmptyParts.count > 1 else {
        return ""
    }
    return nonEmptyParts.dropFirst().joined(separator: " ")
}

// 调用示例
let input1 = "Hello World this is Swift"
print(removeFirstWord(from: input1)) // 输出: World this is Swift

方式二:位置截取子串

性能更优,直接定位第一个空白字符的位置后截取:

func removeFirstWord(_ sentence: String) -> String {
    guard let firstSpace = sentence.rangeOfCharacter(from: .whitespacesAndNewlines) else {
        return ""
    }
    let trimmedSubstring = sentence[firstSpace.upperBound...].trimmingCharacters(in: .whitespacesAndNewlines)
    return String(trimmedSubstring)
}

// 调用示例
let input2 = "  Swift is awesome  "
print(removeFirstWord(input2)) // 输出: is awesome

方式三:正则表达式替换

适合需要灵活匹配规则的场景,比如处理带特殊字符的单词:

import Foundation

func removeFirstWordWithRegex(_ sentence: String) -> String {
    let regexPattern = "^\\s*\\w+\\s*"
    guard let regex = try? NSRegularExpression(pattern: regexPattern) else {
        return sentence
    }
    let fullRange = NSRange(sentence.startIndex..., in: sentence)
    return regex.stringByReplacingMatches(in: sentence, range: fullRange, withTemplate: "")
}

// 调用示例
let input3 = "Hello   everyone let's code"
print(removeFirstWordWithRegex(input3)) // 输出: everyone let's code

内容的提问来源于stack exchange,提问作者Eren

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 18:55:29