我有一个用来保存文本的字段。我要将文本保存在 HTML 文本区域中,但我需要设置行数。
如何计算字符串中的换行数,以便设置 textarea 行?
使用LINQ
:
int lineCount = text.Count(c => c == '\n');
换行符是一个或两个字符,具体取决于系统。在windows系统上是两个字符的组合\r\n
,但是数的时候只能找其中一个。
由于字符串是可枚举的,因此可以使用Count
扩展方法:
int cnt = str.Count(c => c == '\n');
试试这个代码扩展方法。
public class static Extension
{
public static int CountStringOccurrences(this string text, string pattern)
{
// Loop through all instances of the string 'text'.
int count = 0;
int i = 0;
while ((i = text.IndexOf(pattern, i)) != -1)
{
i += pattern.Length;
count++;
}
return count;
}
}
采用
var text = "Sam dfdfgdf Sam.";
text.CountStringOccurrences("Sam"));
您可以使用String.Split
:
int lines = stringVariable.Split('\n').Length + 1;
或者,您可以使用Enumerable.Count
:
int lines = stringVariable.Count(s => s == '\n') + 1;
(这两个示例都假设您的字符串不包含尾随换行符。)
但是,如果您的任何文本行比您的 宽,这不一定会给您所需的内容textarea
,因为它们的文本会换行。
您也可以使用正则表达式
int count = new Regex(@"\n").Matches(inputstr).Count
其他方式;
int lines = str.Length - str.Replace("\n", "").Length;
这将取决于文本区域中的列数。尝试这样的事情:
StringBuilder mystring = new StringBuilder(@"Hey this is a fairly long string which I used in this /
example to show how long strings might be broken up into different lines based on how /
wide your text area is. What is going to happen is we are about to insert a newline /
after however many characters the textarea is wide. We'll also count the number of /
newlines that we put in, and that number plus one will be the number we need for the /
textarea!");
int columnCounter = 0;
int lineCounter= 1; //1 for the first line
const int COLUMNS_IN_TEXT_AREA = howeverManyColsYouHave;
for(int i = 0; i<mystring.Length;i++) //set to less than mystring.length, just in case the string were really short.
{
if(columnCounter >= COLUMNS_IN_TEXTAREA)
{
mystring.Insert(i,"\n");
lineCounter ++;
}
}
现在将字符串生成器和行数作为 JSon 或其他内容发送到您的视图中,瞧!