View Full Version : C# searching strings
patrickcabenjamin
12 Apr 2009, 12:10pm
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?
pragtastic
12 Apr 2009, 12:42pm
It's possible a couple of different ways, the easiest would be utilizing the built in methods (http://msdn.microsoft.com/en-us/library/system.string_methods.aspx) with the string type (the more advanced and powerful way is via regular expressions (http://msdn.microsoft.com/en-us/library/ms228595(VS.80).aspx)).
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);
}
patrickcabenjamin
12 Apr 2009, 1:05pm
thanks
:-)
patrickcabenjamin
12 Apr 2009, 1:09pm
what about if i wanted to find the word after "i am" and make that string1?
would that be possible?
MiracleManS
14 Apr 2009, 4:51pm
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.
pragtastic
15 Apr 2009, 6:24pm
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.
patrickcabenjamin
15 Apr 2009, 7:46pm
how would you write it out in a script?
vBulletin® v3.8.1, Copyright ©2000-2009, Jelsoft Enterprises Ltd.