Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count lines in a string?

Tags:

c#

I am removing text from a string and what to replace each line with a blank line.

Some background: I am writing a compare function that compares two strings. Its all working fine and are displayed in there two separate web browsers. When i try scroll down on my browsers the strings are different lengths, I want to replace the text i am removeing with a blank line so that my strings are the same length.

In the code below i am looking to count how many lines aDiff.Text has

Here is my code:

public string diff_prettyHtmlShowInserts(List<Diff> diffs)     {         StringBuilder html = new StringBuilder();          foreach (Diff aDiff in diffs)         {             string text = aDiff.text.Replace("&", "&amp;").Replace("<", "&lt;")               .Replace(">", "&gt;").Replace("\n", "<br>"); //&para;             switch (aDiff.operation)             {                  case Operation.DELETE:                                                  //foreach('\n' in aDiff.text)                    // {                    //     html.Append("\n"); // Would like to replace each line with a blankline                    // }                     break;                 case Operation.EQUAL:                     html.Append("<span>").Append(text).Append("</span>");                     break;                 case Operation.INSERT:                     html.Append("<ins style=\"background:#e6ffe6;\">").Append(text)                         .Append("</ins>");                     break;             }         }         return html.ToString();     } 
like image 973
Pomster Avatar asked Jun 25 '12 12:06

Pomster


People also ask

How do you count the number of lines in a string?

To count the number of lines of a string in JavaScript, we can use the string split method. const lines = str. split(/\r\n|\r|\n/);

How do you count the number of lines in a string Java?

split("\r\n|\r|\n", -1); if you look at the docs here:docs.oracle.com/javase/7/docs/api/java/lang/… it has more information. since java 1.1 there is a LineNumberReader. see my answer below.

How do you count multiple lines in Python?

Use readlines() to get Line Count This is the most straightforward way to count the number of lines in a text file in Python. The readlines() method reads all lines from a file and stores it in a list. Next, use the len() function to find the length of the list which is nothing but total lines present in a file.


1 Answers

Method 1:

int numLines = aDiff.text.Length - aDiff.text.Replace _                    (Environment.NewLine, string.Empty).Length; 

Method 2:

int numLines = aDiff.text.Split('\n').Length; 

Both will give you number of lines in text.

like image 142
poncha Avatar answered Sep 19 '22 15:09

poncha