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

如何编写函数获取字符串中指定字符(含词间空格)的索引列表

实现获取字符串内空格索引列表的方法

核心逻辑

遍历字符串的每一个字符,同步记录当前字符的索引值,当字符匹配空格时将对应索引存入结果列表即可。

不同语言的实现示例

Python 实现

基础遍历写法

def get_space_indices(input_str: str) -> list:
    space_indices = []
    for index, char in enumerate(input_str):
        # 匹配普通半角空格,若需要匹配所有空白字符可替换为 if char.isspace()
        if char == ' ':
            space_indices.append(index)
    return space_indices

简写列表推导式写法

直接一行即可完成:
[index for index, char in enumerate(input_str) if char == ' ']

测试示例:
输入字符串:"Hello World this is a test"
输出结果:[5, 11, 16, 19, 21]

JavaScript 实现

基础遍历写法

function getSpaceIndices(inputStr) {
    const spaceIndices = [];
    for (let i = 0; i < inputStr.length; i++) {
        // 匹配普通半角空格,若需要匹配所有空白字符可替换为 if (/\s/.test(inputStr[i]))
        if (inputStr[i] === ' ') {
            spaceIndices.push(i);
        }
    }
    return spaceIndices;
}

简写写法

[...inputStr].map((char, idx) => char === ' ' ? idx : -1).filter(idx => idx !== -1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 15:15:03