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

Swift:根据字符串中点击字符的索引获取对应邮箱的起止索引

找到目标索引所在邮箱的起止位置

嘿,这个需求在文本交互场景里挺实用的!核心思路就是定位目标索引周围的分隔符(逗号+空格),以此锁定对应邮箱的边界。我给你整理了清晰的实现逻辑,还附上了Python代码示例:

实现步骤

  1. 向前找起始索引:从目标索引往回遍历,直到遇到逗号/空格或者字符串开头,再跳过前面的分隔符(逗号和空格),就能拿到邮箱第一个字符的索引。
  2. 向后找结束索引:从目标索引往后遍历,直到遇到逗号/空格或者字符串结尾,此时的位置就是邮箱最后一个字符的索引。

代码示例(Python)

def get_email_boundaries(email_string, target_index):
    # 处理边界情况:目标索引超出范围直接返回无效值
    if target_index < 0 or target_index >= len(email_string):
        return (-1, -1)
    
    # 向前遍历找起始位置
    start_index = target_index
    while start_index > 0 and email_string[start_index - 1] not in (',', ' '):
        start_index -= 1
    # 跳过前面的分隔符(逗号和空格)
    while start_index < len(email_string) and email_string[start_index] in (',', ' '):
        start_index += 1
    
    # 向后遍历找结束位置
    end_index = target_index
    while end_index < len(email_string) - 1 and email_string[end_index + 1] not in (',', ' '):
        end_index += 1
    
    return (start_index, end_index)

测试你的例子

用你提供的字符串和目标索引来验证:

original_emails = "jim@domain.com, bill@domain.com, chad@domain.com, tom@domain.com"
target_idx = 39  # 对应chad@domain.com中的'o'
start, end = get_email_boundaries(original_emails, target_idx)
print(f"起始索引: {start}, 结束索引: {end}")

运行后就能得到chad@domain.com的准确起止索引,完全符合你的需求~

边界情况处理

  • 如果目标索引在第一个邮箱(比如jim@domain.com里的字符),函数会自动识别到字符串开头,不会出错。
  • 如果目标索引在最后一个邮箱(比如tom@domain.com里的字符),会遍历到字符串结尾停止。
  • 传入无效索引(超出字符串范围)时,会返回(-1, -1)作为提示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:41:03