zrubi zrubi - 3 months ago 16
C# Question

How to search for specific word into the string

I'm trying to search for specific word into the string, how can I get it for compare. Output is a integer of first character of the founded word, so got integer, but what I can to do with it?

using System;

namespace _01_8
{
class Program
{
static void Main(string[] args)
{
string searchin = "please find searchword1 here";
string searchword = "searchword1";
int firstChar = searchin.IndexOf(searchword);

string myString = firstChar.ToString();

// Console.WriteLine("First index: {0}", firstChar);


so of course I can't convert it to the string with single integer of index on output this way:

string myString = firstChar.ToString();


if I want use it this way for example:

if (myString == "searchword1")
{
Console.WriteLine("it is Searchword One");
}
else if (myString == "searchword2")
{
Console.WriteLine("it is Searchword Two");
}
Console.Read();
}
}
}

Answer

The int result is not the first char of the word, it is the position of the first char of the word, i.e. its index within the string.

If the search-word is always the same, except for the digit following it then I would search only for the alphabetical part and then look what digit follows.

string searchword = "searchword"; // Without the digit.    
int pos = searchin.IndexOf(searchword);
int posOfDigit = pos + searchword.Length;
Console.WriteLine("it is Searchword " + searchin[posOfDigit]);

You can convert the digit to a number name like this

string[] numbers = new string[] { "Zero", "One", "Two", ... "Nine" };
string number = numbers[searchin[posOfDigit] - '0'];

Where we use the fact that C# allows you to perform arithmetic on characters where the character code is used.