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

Swift中如何确定字符串数组内的词或短语在文本块中的首次出现项

如何找到数组中最先出现在文本里的词/短语?

其实这个需求的核心逻辑很清晰:我们需要逐个检查数组里的每个词,记录它们在文本中的起始位置,然后找出位置最靠前的那个词就可以了。之前你找到的方案只能判断是否存在,是因为它没追踪位置信息,我们补上这部分就行。

核心思路拆解

  • 遍历目标数组里的每一个词/短语
  • 对每个词,找到它在文本中的起始索引位置(找不到的就直接忽略)
  • 把所有找到的词和对应的位置存起来
  • 按位置从小到大排序,排在第一个的就是最先出现的词

具体代码实现(以JavaScript为例)

function findFirstOccurrence(searchWords, text) {
  // 存储找到的词及其在文本中的位置
  const matchedItems = [];
  
  for (const word of searchWords) {
    const position = text.indexOf(word);
    // 只保留在文本中存在的词
    if (position !== -1) {
      matchedItems.push({ position, word });
    }
  }

  // 处理没有任何匹配的情况
  if (matchedItems.length === 0) {
    return null; // 或者返回你需要的默认提示,比如"无匹配项"
  }

  // 按位置从小到大排序,取第一个就是最先出现的词
  matchedItems.sort((a, b) => a.position - b.position);
  return matchedItems[0].word;
}

// 验证你的示例
const searchWords = ["December", "Wednesday", "beginning of winter", "Thursday", "summer solstice"];
const text = "This year the start of the summer solstice will be on a Wednesday. And the beginning of winter will start on a Thursday.";

console.log(findFirstOccurrence(searchWords, text)); // 输出:"summer solstice"

Python版本实现

如果你用Python的话,逻辑是完全一样的:

def find_first_occurrence(search_words, text):
    matched_items = []
    for word in search_words:
        position = text.find(word)
        if position != -1:
            matched_items.append((position, word))
    
    if not matched_items:
        return None
    
    # 按位置排序,元组默认按第一个元素排序
    matched_items.sort()
    return matched_items[0][1]

# 验证示例
search_words = ["December", "Wednesday", "beginning of winter", "Thursday", "summer solstice"]
text = "This year the start of the summer solstice will be on a Wednesday. And the beginning of winter will start on a Thursday."

print(find_first_occurrence(search_words, text)) # 输出:"summer solstice"

注意事项

  • 如果数组里有包含关系的词(比如数组里同时有"summer"和"summer solstice"),那indexOf/find会先找到短词的位置,如果你需要优先匹配长短语的话,得先把数组按长度从长到短排序,再进行位置查找,这个可以根据你的实际需求调整。
  • 上述代码是大小写敏感的,如果需要忽略大小写,可以先把文本和搜索词都转成小写(或大写)再进行匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 18:59:08