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?

Recommended Answers

All 2 Replies

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?

Hi,

You may Use regular expression (Regex), for string searching.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.