我如何在foreach循环中分配值给字符变量?c#



我想做的是这样的:

StringBuilder sb = new StringBuilder();
foreach(char ch in valor)
{
if (ch == ',')
ch = '.';
else if (ch == '0' || ch == '1' || ch == '2' || ch == '3' || ch == '4' || ch == '5' || ch == '6' || ch == '7' || ch == '8' || ch == '9' || ch == ',')
{
sb.Append(ch);
}
}

我想要的是,如果字符是逗号,将其设为点。但是我得到以下错误

不能给'ch'赋值,因为它是一个foreach交互变量

为什么不在两个if分支中都添加呢?

foreach(char ch in valor)
{
if (ch == ',')
{
sb.Append('.');
}
else if (ch == '0' || ch == '1' || ch == '2' || ch == '3' || ch == '4' || ch == '5' || ch == '6' || ch == '7' || ch == '8' || ch == '9')
{
sb.Append(ch);
}
}

简短回答:这是不可能的.

使用不可变的foreach索引项,您需要使用如下中间变量:

foreach ( char ch in valor )
{
char c = ch;
if ( c == ',' )
{
c = '.';
}
if ( c == '0' || c == '1' || c == '2' || c == '3' || c == '4'
|| c == '5' || c == '6' || c == '7' || c == '8' || c == '9'
|| c == '.' )
{
sb.Append(c);
}
}

我删除了else,因为它似乎是一个错误…

但是在这种情况下,您可能更喜欢直接使用for来避免这个无用的中间变量,从而优化速度和内存:

for (int index = 0; index < valor.Length; index++)
{
char c = valor[index];
if ( c == ',' )
{
c = '.';
}
if ( c == '0' || c == '1' || c == '2' || c == '3' || c == '4'
|| c == '5' || c == '6' || c == '7' || c == '8' || c == '9'
|| c == '.' )
{
sb.Append(c);
}
}

接下来,对于所提供的代码,我们可以这样重构,现在以正确的方式使用else:

for (int index = 0; index < valor.Length; index++)
{
char c = valor[index];
if ( c == ',' )
{
sb.Append('.');
}
else
if ( c == '0' || c == '1' || c == '2' || c == '3' || c == '4'
|| c == '5' || c == '6' || c == '7' || c == '8' || c == '9' )
{
sb.Append(c);
}
}

同样,对于所提供的代码,我们可以这样改进:

for ( int index = 0; index < valor.Length; index++ )
{
char c = valor[index];
if ( c == ',' )
{
sb.Append('.');
}
else
if ( char.IsDigit(c) )     // or IsNumber
{
sb.Append(c);
}
}

和更好地优化:

for ( int index = 0; index < valor.Length; index++ )
{
char c = valor[index];
if ( c == ',' )
{
sb.Append('.');
}
else
if ( c >= '0' && c <= '9' )
{
sb.Append(c);
}
}

所以使用foreach我们可以写,但更少的优化,但更干净:

foreach (char ch in valor )
{
if ( ch == ',' )
{
sb.Append('.');
}
else
if ( ch >= '0' && ch <= '9' )
{
sb.Append(ch);
}
}

字符。IsDigit方法

字符。IsNumber方法

foreach, in (c# reference)

for (c# reference)

引入一个局部变量

StringBuilder sb = new StringBuilder();
foreach(char ch in valor)
{
var tmp = ch == ',' ? '.' : ch;
if (char.IsDigit(tmp) || tmp == '.')
{
sb.Append(tmp);
}
}

您还可以使用静态char.IsDigit()方法来检查char是否是数字

你也可以只使用linq:

var sb = new StringBuilder();
sb = valor
.Select(c => c == ',' ? '.' : c)
.Where(c => char.IsDigit(c) || c == '.')
.Aggregate(sb, (sb, c) => sb.Append(c));

你可以试试:


StringBuilder sb = new StringBuilder();
var valor = "google,com1234";
if (valor.Contains(','))
{
valor = valor.Replace(",", ".");
}
foreach (char ch in valor)
{
if (ch == '0' || ch == '1' || ch == '2' || ch == '3' || ch == '4' || ch == '5' || ch == '6' || ch == '7' || ch == '8' || ch == '9' || ch == '.')
{
sb.Append(ch);
}
}

相关内容

  • 没有找到相关文章

最新更新