码迷,mamicode.com
首页 > 其他好文 > 详细

与字符串有关的题目

时间:2015-10-21 00:14:08      阅读:255      评论:0      收藏:0      [点我收藏+]

标签:

1、统计某种字符串中某个字符或某个字符串出现的次数,以及每次出现的索引位置

有如下字符串:【"患者:“大夫,我咳嗽得很重。”
* 大夫:“你多大年记?” 患者:“七十五岁。”
* 大夫:“二十岁咳嗽吗”患者:“不咳嗽。”
* 大夫:“四十岁时咳嗽吗?” 患者:“也不咳嗽。”
* 大夫:“那现在不咳嗽,还要等到什么时咳嗽?”"】。
* 需求:请统计出该字符中“咳嗽”二字的出现次数,
* 以及每次“咳嗽”出现的索引位置。*/

        static void GetCough(string str)
        {
            int n = 0;
            int nStartIndex = 0;
            while (true)
            {
                int index = str.IndexOf("咳嗽", nStartIndex);
                if (-1 == index)
                {
                    break;
                }
                else
                {
                    n++;
                    nStartIndex = index + 2;
                    Console.WriteLine("第{0}次咳嗽出现的位置是{1}",n,index);
                }
            }
        }

2、去掉空格,替换空格类型

  一般调用string的Trim方法去掉字符串前面和后面两边的空格,去掉前面的空格用TrimStart,去掉后面的空格用TrimEnd。

  将字符串中间的空格去掉可以先用Split将字符串分割成若干个子串,再用Join将这些子串连接成一个字符串。

       /*20.    将字符串"  hello      world,你  好 世界   !    "两端空格去掉,
         * 并且将其中的所有其他空格都替换成一个空格,
         * 输出结果为:"hello world,你 好 世界 !"。   */
        static void Main(string[] args)
        {
            string str = "  hello      world,你  好 世界   !    ";
            Console.WriteLine("输出结果: {0}", DealString(str));
            Console.ReadKey();
        }

        static string DealString(string strSrc) 
        {
            string strDesc = strSrc.Trim();
            string[] strs = strDesc.Split(new char[] { },StringSplitOptions.RemoveEmptyEntries);
            string strRes = string.Join(" ",strs);
            return strRes;
        }

        //程序运行的过程中会产生无用的string,占据内存。
        //static string DealString(string strSrc)
        //{
        //    string strDesc = strSrc.Trim();
        //    for (int i = 0; i < strDesc.Length - 1;)
        //    {   //遇到连续空格的话,就删掉前面一个
        //        if (strDesc[i] == ‘ ‘ && strDesc[i+1] == ‘ ‘)
        //        {
        //            strDesc = strDesc.Remove(i, 1);
        //        }
        //        else
        //        {
        //            i++;
        //        }
        //    }
        //    return strDesc;
        //}

 

与字符串有关的题目

标签:

原文地址:http://www.cnblogs.com/lcxBlog/p/4896332.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!