0

i have been having trouble searching string for a specified char. I have been using the string.indexOf(char) but that only gives me the index of the first instance of the char not all the index values of the char.
for example..

string wordToSearch = "adadda";
if(wordToSearch.indexOf("a")) != -1) 
messagebox.show("letter is not found in selected word");
else
{
//this displays only the first "a" of the string but i need to know the index values of 
//all the "a"s in the string
messagebox.show("letter is found at " + wordToSearch.indexOf("a").toString());
}

or is this even possible without converting my string to an array of char values?

3
Contributors
2
Replies
3
Views
9 Years
Discussion Span
Last Post by selvaganapathy
0

Then you need to use one of the other overloads.. such as

List<int> locs = new List<int>();
int loc = -1;
do
{
loc = wordToSearch.Indexof('a',loc+1);
if (a>-1) { locs.add(loc); }
} while (loc > -1 );

or, you could take a simpler approach and just do

foreach (char c in myString)
{
  if (c=='a') { count++; }
}

depending on what you needed.

Also - wouldnt

if(wordToSearch.indexOf("a")) != -1)

be when its FOUND the string, not when its not?

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.