A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 郑志强 中级黑马   /  2013-3-11 22:03  /  1423 人查看  /  6 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 郑志强 于 2013-3-12 20:14 编辑

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

拜托了。

评分

参与人数 1技术分 +1 收起 理由
张文 + 1

查看全部评分

6 个回复

倒序浏览
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.

评分

参与人数 1技术分 +1 收起 理由
张文 + 1

查看全部评分

回复 使用道具 举报
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);
                }
            }

评分

参与人数 1技术分 +1 收起 理由
张文 + 1

查看全部评分

回复 使用道具 举报
曾玉锋 发表于 2013-3-11 23:54
string str = "abddeafaeaeafafafe";
            List list = new List();//用于存储e的位置
             ...

你好,能把你的代码写完整吗,针对提问者提出的问题.
回复 使用道具 举报
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]);
          }
}
回复 使用道具 举报
完整代码:
  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.         }
复制代码

评分

参与人数 1技术分 +1 收起 理由
张文 + 1

查看全部评分

回复 使用道具 举报
如果不用for循环有没有其他办法?
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马