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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 帕格尼尼的眼泪 中级黑马   /  2013-7-23 23:05  /  1474 人查看  /  6 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

一个字符串android and ios,怎么让它在控制台窗口输出所有d的位置,用string方法

6 个回复

倒序浏览
这个问题我好像在phyth里学过,{:soso_e134:}忘记了。
C#的基础视频我刚开始学,还没学到srting方法的内容,以下是猜测:
string应该有一个方法string.index(),可以得到某字符在串中的索引位置,用它遍历字符串就好了。
回复 使用道具 举报
本帖最后由 黑骏马 于 2013-7-24 01:24 编辑

查了下MSDN,MSDN真是个好东西{:soso_e113:}。

如何:使用字符串方法搜索字符串(C# 编程指南)http://msdn.microsoft.com/zh-cn/library/vstudio/ms228630.aspx
  1. string str = "android and ios";
  2. System.Console.WriteLine(str);

  3. //IndexOf()方法可以得到字符在串中的索引位置
  4. int dindex = str.IndexOf("d") ;
  5. System.Console.WriteLine(dindex);

  6. System.Console.ReadKey();
复制代码
{:soso_e127:}只能得到第一个d的位置,我只能想到用截取字符串片段的方法和用其它字母替换已找到的d这两种方法得到后面的。我不会遍历字符串,请教该怎么遍历字符串?

评分

参与人数 1技术分 +1 收起 理由
zhangcheng5468 + 1 再研究研究,争取能给出完整地答案.

查看全部评分

回复 使用道具 举报
黑骏马 发表于 2013-7-24 01:18
查了下MSDN,MSDN真是个好东西。

如何:使用字符串方法搜索字符串(C# 编程指南)http://msd ...
  1. Char[] chars = s2.ToCharArray();
  2.             
  3.             for (int i = 0; i < chars.Length; i++)
  4.             {
  5.                     if(chars[i] == 'd')
  6.                     {
  7.                             Console.WriteLine(i);
  8.                     }
  9.             }
复制代码
回复 使用道具 举报
当然也可以用正则
  1. string s2  = "android and ios";
  2.             
  3.             Regex reg = new Regex("d");
  4.             
  5.             Match m = reg.Match(s2, 0);
  6.             
  7.             while (m.Success)
  8.             {
  9.                     Console.WriteLine(m.Index);
  10.                     m = m.NextMatch();
  11.             }
复制代码

评分

参与人数 1技术分 +1 收起 理由
zhangcheng5468 + 1 赞一个!最好按照楼主的问题来

查看全部评分

回复 使用道具 举报
using System;
namespace Question
{
    class Program
    {
        public static void Main(string[] args)
        {
            string string_1 = "android and ios";
            char[] charArray_1 = string_1.ToCharArray();
            for(int i = 0;i<charArray_1.Length;i++)
            {
                if(charArray_1[i] == 'd')
                {
                     Console.WriteLine(i);
                }
            }
            Console.ReadKey();
        }
    }
}

评分

参与人数 1技术分 +1 收起 理由
zhangcheng5468 + 1 新童鞋,以后回复先把楼上各位的意见看看说.

查看全部评分

回复 使用道具 举报
你可以把字符串拆分放到一个char数组里面,然后用for遍历数组,用if判断是不是d。  代码见楼上。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马