我该如何在C#中计算字符串开头的空格数?
例如:
" this is a string"
结果将是4。不确定如何正确执行此操作。
谢谢。
我该如何在C#中计算字符串开头的空格数?
例如:
" this is a string"
结果将是4。不确定如何正确执行此操作。
谢谢。
Enumerable.TakeWhile
、Char.IsWhiteSpace
和 Enumerable.Count
。int count = str.TakeWhile(Char.IsWhiteSpace).Count();
" "
是空格但是:......所以基本上是空格、换行和制表符
你可以使用 LINQ,因为 string
实现了 IEnumerable<char>
:
var numberOfSpaces = input.TakeWhile(c => c == ' ').Count();
input.TakeWhile(c => c == ' ').Count()
input.Length - input.TrimStart(' ').Length
TrimStart
的解决方案是最简单的。 - helrichTrimStart
内部使用了Char.IsWhiteSpace
。在input=" \t text"
上进行检查。第一个返回1,第二个返回3,因为制表符被计算为空格。 - Tim Schmelterinput.Length - input.TrimStart(' ').Length
以获得与第一行相同的结果。 - Andreas AdlerTakeWhile(Char.IsWhiteSpace).Count()
更简单(一旦你理解了字符串是一个 IEnumerable<char>
)。 - Tim SchmelterTrimStart
会将 \t
和 \r
视为空格。 - Sergey Berezovskiy试试这个:
static void Main(string[] args)
{
string s = " this is a string";
Console.WriteLine(count(s));
}
static int count(string s)
{
int total = 0;
for (int i = 0; i < s.Length; i++)
{
if (s[i] == ' ')
total++;
else
break;
}
return total;
}
for
еңҒзҺҮж”№дёғwhile
еңҒзҺҮдәљж›өзџгЂ‚ - iCollect.it Ltd虽然我喜欢基于Linq的答案,但这里有一个无聊的不安全方法,应该非常快
private static unsafe int HowManyLeadingSpaces(string input)
{
if (input == null)
return 0;
if (input.Length == 0)
return 0;
if (string.IsNullOrWhiteSpace(input))
return input.Length;
int count = 0;
fixed (char* unsafeChar = input)
{
for (int i = 0; i < input.Length; i++)
{
if (char.IsWhiteSpace((char)(*(unsafeChar + i))))
count++;
else
break;
}
}
return count;
}
int count = 0, index = 0, lastIndex = 0;
string s = " this is a string";
index = s.IndexOf(" ");
while (index > -1)
{
count++;
index = s.IndexOf(" ", index + 1);
if ((index - lastIndex) > 1)
break;
lastIndex = index;
}
Console.WriteLine(count);