Home > Blockchain >  how to find text in a string in c#
how to find text in a string in c#

Time:08-20

I am learning Dotnet c# on my own. how to find whether a given text exists or not in a string and if exists, how to find count of times the word has got repeated in that string. even if the word is misspelled, how to find it and print that the word is misspelled? we can do this with collections or linq in c# but here i used string class and used contains method but iam struck after that.

if we can do this with help of linq, how? because linq works with collections, Right? you need a list in order to play with linq. but here we are playing with string(paragraph). how linq can be used find a word in paragraph? kindly help.

here is what i have tried so far.

 string str = "money makes many things";
    for(int i = 0; i < i  )
    if (str.Contains("makes") == true)
    {
              
        Console.WriteLine("found");
        
    }
    else
    {
        Console.WriteLine("not found");
    }

CodePudding user response:

You can make a string a string[] by splitting it by a character/string. Then you can use LINQ:

if(str.Split().Contains("makes"))
{
    // note that the default Split without arguments also includes tabs and new-lines
}

If you don't care whether it is a word or just a sub-string, you can use str.Contains("makes") directly.

If you want to compare in a case insensitive way, use the overload of Contains:

if(str.Split().Contains("makes", StringComparer.InvariantCultureIgnoreCase)){}

CodePudding user response:

string str = "money makes many makes things";
var strArray = str.Split(" ");
var count = strArray.Count(x => x == "makes");

CodePudding user response:

the simplest way is to use Split extension to split the string into an array of words.

here is an example :

var words = str.Split(' ');

if(words.Length > 0)
{
    foreach(var word in words)
    {
        if(word.IndexOf("makes", StringComparison.InvariantCultureIgnoreCase) != -1)
        {
            Console.WriteLine("found");
        }
        else
        {
            Console.WriteLine("not found");
        }   
    }   
}

Now, since you just want the count of number word occurrences, you can use LINQ to do that in a single line like this :

var totalOccurrences = str.Split(' ').Count(x=> x.IndexOf("makes", StringComparison.InvariantCultureIgnoreCase) != -1);

Note that StringComparison.InvariantCultureIgnoreCase is required if you want a case-insensitive comparison.

  • Related