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

如何查找字符串中指定字符的第n次出现位置?

如何查找字符串中特定字符的第n次出现位置

当然可以,下面给几种实用的实现思路和代码示例,以Python和JavaScript为例:

方法一:手动遍历计数

遍历字符串的每个字符,遇到目标字符就增加计数器,当计数器等于n时,返回当前字符的索引;如果遍历结束都没达到n次,返回-1表示不存在。

Python实现:

def find_nth_occurrence(s, target_char, n):
    count = 0
    for idx, char in enumerate(s):
        if char == target_char:
            count += 1
            if count == n:
                return idx
    return -1  # 未找到第n次出现

# 示例测试
test_str = "abcdefg"
print(find_nth_occurrence(test_str, 'a', 1))  # 输出:0
print(find_nth_occurrence(test_str, 'a', 2))  # 输出:-1(该字符串仅含1个'a')

JavaScript实现:

function findNthOccurrence(str, targetChar, n) {
    let count = 0;
    for (let i = 0; i < str.length; i++) {
        if (str[i] === targetChar) {
            count++;
            if (count === n) {
                return i;
            }
        }
    }
    return -1;
}

// 示例测试
const testStr = "abcdefg";
console.log(findNthOccurrence(testStr, 'a', 1)); // 输出:0
console.log(findNthOccurrence(testStr, 'a', 2)); // 输出:-1

方法二:利用字符串内置查找方法循环定位

借助字符串的find(Python)或indexOf(JavaScript)方法,每次从上次找到的位置的下一位开始查找,循环n次后得到结果。

Python实现:

def find_nth_occurrence(s, target_char, n):
    current_pos = -1
    for _ in range(n):
        current_pos = s.find(target_char, current_pos + 1)
        if current_pos == -1:
            break
    return current_pos

# 示例测试
test_str = "abcdefg"
print(find_nth_occurrence(test_str, 'a', 1))  # 输出:0
print(find_nth_occurrence(test_str, 'a', 2))  # 输出:-1

JavaScript实现:

function findNthOccurrence(str, targetChar, n) {
    let currentPos = -1;
    for (let i = 0; i < n; i++) {
        currentPos = str.indexOf(targetChar, currentPos + 1);
        if (currentPos === -1) break;
    }
    return currentPos;
}

// 示例测试
const testStr = "abcdefg";
console.log(findNthOccurrence(testStr, 'a', 1)); // 输出:0
console.log(findNthOccurrence(testStr, 'a', 2)); // 输出:-1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 01:41:05