skip to Main Content

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 = "Education is a ray of light in the darkness. It certainly is a hope for a good life. Eudcation is a basic right of every Human on this Planet. To deny this right is evil. Uneducated youth is the worst thing for Humanity. Above all, the governments of all countries must ensure to spread Education";
    for(int i = 0; i < i++)
    if (str.Contains("Education") == true)
    {
              
        Console.WriteLine("found");
        
    }
    else
    {
        Console.WriteLine("not found");
    }

3

Answers


  1. string str = "money makes many makes things";
    var strArray = str.Split(" ");
    var count = strArray.Count(x => x == "makes");
    
    Login or Signup to reply.
  2. 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)){}
    
    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search