Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 字符串计数前缀空间中字符前的前导空格_C#_.net_Linq - Fatal编程技术网

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();