简体   繁体   中英

Using Indexof to check if string contains a character

What I'm trying to do is type in random words into box1, click a button and then print all the words that start with "D" in box2. So if I was to type in something like "Carrots Doors Apples Desks Dogs Carpet" and click the button "Doors Desks Dogs" would print in box2.

    string s = box1.Text;                
    int i = s.IndexOf("D");
    string e = s.Substring(i);
    box2.Text = (e);

when I use this^^
It would print out "Doors Apples Desks Dogs Carpet" instead of just the D's.
NOTE: These words are an example, I could type anything into box1.

Any help?

You could simplify this by using LINQ

var allDWords = box1.Text.Split(' ').Where(w => w.StartsWith("D"));
box2.Text = String.Join(" ", allDWords);

Try this

box2.Text = String.Join(" ", 
                box1.Text.Split(' ')
                         .Where(p => p.StartsWith("D")));

You can match the D words with a regular expression and iterate over the results

Try this regex

D\w+

First you need to split up the text into words and then check to see if each word starts with D . When looking for the first character it's easier to just check it directly.

string s = box1.Text;  
StringBuilder builder = new StringBuilder();
foreach (var cur in s.Split(new char[] { ' ' })) {
  if (cur.Length > 0 && cur[0] == 'D') {
    builder.Append(cur);
    builder.Append(' ');
  }
}
box2.Text = builder.ToString();

One thing you could do is:

Lets suppose,

 string str = "Dog Cat Man etc";
            string[] words = str.Split(' ');

            List<string> wordStartWithD = new List<string>();

            foreach (string strTemp in words)
                if (strTemp.StartsWith("D"))
                    wordStartWithD.Add(strTemp);

Hope this help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM