vb.net 如何计算输入字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13852432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to count Enter in a string?
提问by user576510
Possible Duplicate:
How would you count occurences of a string within a string (C#)?
可能的重复:
您将如何计算字符串中字符串的出现次数 (C#)?
I have a string that has multiple sub-strings and Enter (special character by pressing Enter key) between them.
我有一个字符串,其中包含多个子字符串和 Enter(按 Enter 键的特殊字符)。
Can you please guide me how to write a regular expression that counts Enter keys between words ?
你能指导我如何编写一个计算单词之间 Enter 键的正则表达式吗?
Thanks
谢谢
回答by Daniel Brückner
Depending on the line break symbol used you may have to change to just \ror just \n.
根据使用的换行符,您可能需要更改为 just\r或 just \n。
var numberLineBreaks = Regex.Matches(input, @"\r\n").Count;
回答by ean5533
You don't need a regex, you're just counting strings. Specifically you're just counting Environment.Newlines. There's lots of ways to do that; several are described in this SO answer. Here's one which looks inefficient but performs surprisingly well:
你不需要正则表达式,你只是在计算字符串。具体来说,您只是在计算Environment.Newlines。有很多方法可以做到这一点;在这个 SO answer中描述了几个。这是一个看起来效率低下但表现出奇的好:
int count1 = source.Length - source.Replace(Environment.Newline, "").Length;
回答by Tim Long
Does it have to be a regular expression? There are probably easier ways... for example, you could use string[] array = String.Split('\n');to create an array of the substrings, then get the count with array.Length;
它必须是正则表达式吗?可能有更简单的方法......例如,您可以使用string[] array = String.Split('\n');创建一个子字符串数组,然后使用array.Length;
回答by neeKo
You could do by simply counting the newlines:
您可以通过简单地计算换行符来完成:
int start = -1;
int count = 0;
while ((start = text.IndexOf(Environment.NewLine, start + 1)) != -1)
count++;
return count;
回答by Morteza Azizi
You can use this Code,
您可以使用此代码,
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
long a = CountLinesInString("This is an\r\nawesome website.");
Console.WriteLine(a);
long b = CountLinesInStringSlow("This is an awesome\r\nwebsite.\r\nYeah.");
Console.WriteLine(b);
}
static long CountLinesInString(string s)
{
long count = 1;
int start = 0;
while ((start = s.IndexOf('\n', start)) != -1)
{
count++;
start++;
}
return count;
}
static long CountLinesInStringSlow(string s)
{
Regex r = new Regex("\n", RegexOptions.Multiline);
MatchCollection mc = r.Matches(s);
return mc.Count + 1;
}
}

