C#。如何编写可以在字符串中搜索字符串并返回出现次数的函数? [英] C#. How do I write a function that can search a string within a string and return the number of occurrences?

查看:196
本文介绍了C#。如何编写可以在字符串中搜索字符串并返回出现次数的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨!我需要一些帮助来解决这个问题。我需要在字符串中搜索字符串并返回出现次数。我已经尝试了下面的代码,它的工作原理,我也尝试使用正则表达式,它工作,但我的老师说,假装我不能使用indexOF或正则表达式。请问有什么想法吗?



我的尝试:



< pre lang =c#> 命名空间 ConsoleApplication3
{
class 程序
{
静态 void Main( string [] args)
{
string s1 = < span class =code-string> hellohjhghello;
string s2 = he;
var r =出现次数(s1,s2);
Console.WriteLine( {0}重复{1}次,s2, R);
}
静态 int 出现次数( string s1, string s2)
{
int count = 0 ;
int pos = 0 ;
while ((pos = s1.IndexOf(s2,pos))> -1 )
{
count ++;
pos + = s2.Length;
}
返回计数;
}
}
}

解决方案

你可以试试这个:

  int  count = s1.Split(' 他')。长度 -   1 ; 





或者你也可以使用LINQ



 s1.Count(x = >  x == ' 他'); 


Hi! I need some help figure this one out. I need to search a string within a string and return the number of occurrences. I have tried the code below and it works and i also tried to use a regex and it worked but my teacher said to pretend that i can't use the indexOF or the regex. So any ideas please?

What I have tried:

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            string s1 = "hellohjhghello";
            string s2 = "he";
            var r = Occurrences(s1, s2);
            Console.WriteLine("{0} is repeated {1} times", s2, r);
        }
        static int Occurrences(string s1, string s2)
        {
            int count = 0;
            int pos = 0;
            while((pos = s1.IndexOf(s2,pos)) > -1)
                {
                count++;
                pos += s2.Length;
            }
            return count;
        }
    }
}

解决方案

You can try this:

int count = s1.Split('he').Length - 1;



Or you can also use LINQ

s1.Count(x => x == 'he');


这篇关于C#。如何编写可以在字符串中搜索字符串并返回出现次数的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆