C# searching strings

Hi

In C# i am a complete noob and i know very little, How do you search for a particular word in a string in a console application and make that the value of the string.

for example

System.Console.Out.WriteLine("how are you");
string1 = System.Console.In.ReadLine();
//here it would find if the word good is in string1 but they might have //written i am good
//now string1 would be good rather than i am good
{
System.Console.Out.WriteLine("oh you are " + string1);
}


is this possible? and if so how?

Comments

  • pragtasticpragtastic Alexandria, VA Icrontian
    edited April 2009
    It's possible a couple of different ways, the easiest would be utilizing the built in methods with the string type (the more advanced and powerful way is via regular expressions).
    System.Console.Out.WriteLine("how are you");
    string1 = System.Console.In.ReadLine();
    //here it would find if the word good is in string1 but they might have //written i am good
    //now string1 would be good rather than i am good
    if(string1.ToLower().Contains("good"))
    {
      string1 = "good";
    }
    System.Console.Out.WriteLine("oh you are " + string1);
    }
    
  • edited April 2009
    thanks
    :-)
  • edited April 2009
    what about if i wanted to find the word after "i am" and make that string1?
    would that be possible?
  • MiracleManSMiracleManS Chambersburg, PA Icrontian
    edited April 2009
    You could if you simply found the character location of the match, namely something like

    string1.ToLower().Contains("i am") and find the index of the m in "i am", add 1, and voila.

    I'm not totally familiar with C#, but it would be possible, easily.
  • pragtasticpragtastic Alexandria, VA Icrontian
    edited April 2009
    Personally, I'd do a Regex match on "i am" and then grab the group after it, something like say:

    /i am([\s\w]*)/

    Which should effectively capture any space or word characters proceeding the match of "i am".

    Disclaimer: Regex was written on the fly, as a general rule of thumb, you'll never get your Regex right on the first try.
  • edited April 2009
    how would you write it out in a script?
Sign In or Register to comment.