黑马程序员技术交流社区

标题: 关于寻找 某个字符在字符串里的位置 [打印本页]

作者: 郑志强    时间: 2013-3-11 22:03
标题: 关于寻找 某个字符在字符串里的位置
本帖最后由 郑志强 于 2013-3-12 20:14 编辑

string s="asdfasdferqwergadfqe"
找出e所在位置 很有多少个e

拜托了。
作者: luxun1912    时间: 2013-3-11 22:39
1、先找第一个'e'的位置
string name = "asdfasdferqwergadfqe";
            int index = name.IndexOf('e');
            Console.WriteLine("第1次,e位置是{0}",index);
2、循环找出其他的位置
            int i = 1;
            while (index != -1)
            {
                i++;
                index = name.IndexOf('e', index + 1);
                Console.WriteLine("第{0}次,e的位置是{1}", i, index);
            }
3、当字符串中没有查询的值时候,indeof()方法返回-1.
作者: 曾玉锋    时间: 2013-3-11 23:54
string str = "abddeafaeaeafafafe";
            List<int> list = new List<int>();//用于存储e的位置
            for (int i = 0; i < str.Length;i++ )
            {
                if(str[i]=='e')
                {
                    list.Add(i);
                }
            }
作者: 孔健    时间: 2013-3-12 00:26
曾玉锋 发表于 2013-3-11 23:54
string str = "abddeafaeaeafafafe";
            List list = new List();//用于存储e的位置
             ...

你好,能把你的代码写完整吗,针对提问者提出的问题.
作者: 曾玉锋    时间: 2013-3-12 09:11
public static void Main(string[] args)
{
            string str = "abddeafaeaeafafafe";
            List<int> list = new List<int>();//用于存储e的位置
        //遍历字符串中的每一个字符
        for (int i = 0; i < str.Length;i++ )
            {
                if(str[i]=='e')
                {
                    list.Add(i);
                }
            }
           //遍历字符e在字符串中的所有下标位置
           for(int index=0;index<list.Count;index++)
          {
               Console.WriteLine(list[index]);
          }
}
作者: 孔健    时间: 2013-3-12 11:34
完整代码:
  1. static void Main(string[] args)
  2.         {
  3.             string str = "asdfasdferqwergadfqe";
  4.             List<int> list = new List<int>();//用于存储e的位置
  5.             //遍历字符串中的每一个字符
  6.             for (int i = 0; i < str.Length; i++)
  7.             {              
  8.                 if (str[i] == 'e')
  9.                 {
  10.                     list.Add(i);                    
  11.                 }
  12.             }
  13.             //遍历字符e在字符串中的所有下标位置
  14.             for (int index = 0,i=1; index < list.Count; index++,i++)
  15.             {               
  16.                 Console.WriteLine("共有{0}个e,第{1}次出现位置的索引为:{2}",list.Count, i, list[index]);               
  17.             }         
  18.             Console.ReadKey();
  19.         }
复制代码

作者: 郑志强    时间: 2013-3-12 19:37
如果不用for循环有没有其他办法?




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2