0

我有一个用来保存文本的字段。我要将文本保存在 HTML 文本区域中,但我需要设置行数。

如何计算字符串中的换行数,以便设置 textarea 行?

4

7 回答 7

1

使用LINQ

int lineCount = text.Count(c => c == '\n');
于 2012-08-03T14:47:49.220 回答
1

换行符是一个或两个字符,具体取决于系统。在windows系统上是两个字符的组合\r\n,但是数的时候只能找其中一个。

由于字符串是可枚举的,因此可以使用Count扩展方法:

int cnt = str.Count(c => c == '\n');
于 2012-08-03T14:48:46.257 回答
0

试试这个代码扩展方法。

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"));
于 2012-08-03T14:43:14.313 回答
0

您可以使用String.Split

int lines = stringVariable.Split('\n').Length + 1;

或者,您可以使用Enumerable.Count

int lines = stringVariable.Count(s => s == '\n') + 1;

(这两个示例都假设您的字符串不包含尾随换行符。)

但是,如果您的任何文本行比您的 宽,这不一定会给您所需的内容textarea,因为它们的文本会换行。

于 2012-08-03T14:46:17.303 回答
0

您也可以使用正则表达式

int count =  new Regex(@"\n").Matches(inputstr).Count
于 2012-08-03T14:47:24.053 回答
0

其他方式;

 int lines = str.Length - str.Replace("\n", "").Length;
于 2012-08-03T14:50:54.663 回答
-1

这将取决于文本区域中的列数。尝试这样的事情:

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 或其他内容发送到您的视图中,瞧!

于 2012-08-03T14:54:18.657 回答