find the first index of a character in a string in csharp

To find the first index of a character in a string in C#, you can use the IndexOf() method provided by the String class. This method takes a single character as an argument and returns the index of the first occurrence of that character in the string, or -1 if the character is not found. Here's an example:

main.cs
string myString = "hello world";
char myChar = 'o';
int index = myString.IndexOf(myChar);
Console.WriteLine("Index of first '{0}' character: {1}", myChar, index);
163 chars
5 lines

In this example, the IndexOf() method is used to find the first occurrence of the character 'o' in the string "hello world". The resulting index of 4 is then printed to the console.

Keep in mind that IndexOf() is case-sensitive, so if you want to find the first occurrence of a character regardless of case, you can convert both the string and the character to lowercase using the ToLower() method before calling IndexOf().

gistlibby LogSnag