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

C#中获取字符串中每个'+'字符对应索引的问题求助

解决C#中遍历字符串无法获取每个特定字符对应索引的问题

嘿,这个坑我之前踩过!你的代码里每次都返回第一个+的索引,问题出在expression.IndexOf(c)这个方法上——它的默认行为是从字符串的起始位置开始查找第一个匹配的字符,所以不管你遍历到第几个+,它都会返回第一个+的位置,自然无法得到当前遍历到的那个+的真实索引。

给你两种简单的修改方案,任选其一就行:

方案1:使用for循环直接遍历索引

这种方式最直观,直接操作字符串的索引位置,能准确拿到每个+对应的索引:

using System;
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("enter");
            string expression = Console.ReadLine();
            // 遍历字符串的每个索引位置
            for (int i = 0; i < expression.Length; i++)
            {
                if (expression[i] == '+')
                {
                    Console.WriteLine("plus detected! :{0}", i);
                }
            }
            Console.ReadLine();
        }
    }
}

方案2:在foreach中维护索引变量

如果你更喜欢foreach的简洁写法,可以额外声明一个变量来跟踪当前遍历的索引位置:

using System;
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("enter");
            string expression = Console.ReadLine();
            int currentIndex = 0; // 用来跟踪当前遍历的位置
            foreach(char c in expression)
            {
                if (c == '+')
                {
                    Console.WriteLine("plus detected! :{0}", currentIndex);
                }
                currentIndex++; // 每遍历一个字符,索引自增
            }
            Console.ReadLine();
        }
    }
}

两种方法都能完美解决你的问题,运行后输入包含多个+的字符串,就能看到每个+对应的正确索引啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:05:14