C# 字符串计数前缀空间中字符前的前导空格
我有一根绳子C# 字符串计数前缀空间中字符前的前导空格,c#,.net,linq,C#,.net,Linq,我有一根绳子 -123 我需要得到2作为计数 -12& 3 我需要得到4作为计数。(在这种情况下,我需要3个空格,即在“-”之前) 我使用的代码是 stringValue.Count(countSpace => countSpace == ' '); 如何通过约束检查,即本例中的“-”破折号,并获取“-”破折号之前和“-”之后的空格假设有一个或零个破折号,这将
-123
我需要得到2作为计数
-12& 3
我需要得到4作为计数。(在这种情况下,我需要3个空格,即在“-”之前)
我使用的代码是
stringValue.Count(countSpace => countSpace == ' ');
如何通过约束检查,即本例中的“-”破折号,并获取“-”破折号之前和“-”之后的空格假设有一个或零个破折号,这将起作用:
public static int CountSurroundingSpaces(string stringValue, char constraint)
{
return stringValue.SkipWhile( c => c != constraint)
.Skip(1)
.TakeWhile( c => c == ' ')
.Count() +
stringValue.Reverse()
.SkipWhile( c => c != constraint)
.Skip(1)
.TakeWhile( c => c == ' ')
.Count();
}
您可以使用TrimStart()方法获取原始字符串(不带尾随空格),然后计算原始字符串和修剪字符串的长度差:
stringValue.Length - stringValue.TrimStart().Length
编辑
要计算由某个分隔符拆分的字符串中的空格数,请尝试以下操作:
static IEnumerable<int> GetSpaceCounts(string stringValue, char separator)
{
return stringValue.Split(separator).Select(s => s.Count(c => c == ' '));
}
试着重新表述你的问题,你想要的不是很清楚。我们需要担心有多个破折号吗?另外,你需要破折号周围的空格数,对吗?
string stringValue = " -123 12- ";
foreach (int i in GetSpaceCounts(stringValue, '-'))
Console.WriteLine(i);
Console.ReadLine();