简体   繁体   中英

Foreach Loop Checking For a Specific Character C#

This is a really basic question but for whatever reason I can't figure this out. The program is returning

Error 1 Type and identifier are both required in a foreach statement

int i = 0;
char g = '.';
char s1 = '!';
char s2 = '?';

foreach(g in textBox1.Text)
{
   i++;
}

I know I repeated a variable I am trying to get g to be define as something for example to explain I will put the code to everyday language below

foreach(Period in textBox1.Text)
{
   i++;
}

//Answer there are 3 sentences in textbox 1

foreach(g in textBox1.Text)

You need to define the type for g

ie

foreach(char g in textBox1.Text)

and you have also mistakenly used the variable g twice, the foreach must have type included so one of the g's will have to change it's name

The syntax for a foreach loop indicates that you must declare the variable type within the foreach loop. Take a look at the MSDN implementation . You have two options:

A:

foreach(var c in textBox1.Text)
{
     // Boop.
}

B:

foreach(char c in textBox1.Text)
{
     // Boop.
}

Also answered here , here and here .

Last thing, here is a better way of initializing characters:

char c = '\0';

This is what is null in the ASCII table .

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