计算字符串开头的空格
我如何计算C#中字符串开头的空格量?
例:
" this is a string"
结果将是4.不确定如何正确地做到这一点。
谢谢。
使用Enumerable.TakeWhile
, Char.IsWhiteSpace
和Enumerable.Count
int count = str.TakeWhile(Char.IsWhiteSpace).Count();
请注意,不仅" "
是一个空格, 而且 :
空格字符是以下Unicode字符:
- SpaceSeparator类别的成员,包括字符SPACE(U + 0020),OGHAM SPACE MARK(U + 1680),MONGOLIAN VOWEL SEPARATOR(U + 180E),EN QUAD(U + 2000),EM QUAD(U + 2001) ,EN SPACE(U + 2002),EM SPACE(U + 2003),每三个空间(U + 2004),每四个空间(U + 2005),每六个空间(U +) 2006),数字空间(U + 2007),PUNCTUATION SPACE(U + 2008),THIN SPACE(U + 2009),头发空间(U + 200A),NARROW NO-BREAK SPACE(U + 202F),MEDIUM MATHEMATICAL SPACE( U + 205F)和IDEOGRAPHIC SPACE(U + 3000)。
- LineSeparator类别的成员,仅由LINE SEPARATOR字符(U + 2028)组成。
- ParagraphSeparator类别的成员,仅包含PARAGRAPH SEPARATOR字符(U + 2029)。 字符CHARACTER TABULATION(U + 0009),LINE FEED(U + 000A),LINE TABULATION(U + 000B),FORM FEED(U + 000C),CARRIAGE RETURN(U + 000D),NEXT LINE(U + 0085),和NO-BREAK SPACE(U + 00A0)。
你可以使用LINQ,因为string
实现了IEnumerable
:
var numberOfSpaces = input.TakeWhile(c => c == ' ').Count();
input.TakeWhile(c => c == ' ').Count()
要么
input.Length - input.TrimStart(' ').Length
试试这个:
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; }
虽然我喜欢基于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);