In C# i am making a simple text editor with line numbers. I want to count the ammount of valid line breaks in a string.
i want to count
\r \n \r\n
How can i do this?
Or better yet, can someone point me to an article on how to line number an rtf box
In C# i am making a simple text editor with line numbers. I want to count the ammount of valid line breaks in a string.
i want to count
\r \n \r\n
How can i do this?
Or better yet, can someone point me to an article on how to line number an rtf box
Counting occurrences of a string:
public static int CountStringOccurrences(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;
}
There are articles on CodeProject for this:
Line Numbering of RichTextBox in .NET 2.0
Counting Lines - http://ryanfarley.com/blog/archive/2004/04/07/511.aspx
RTB With Line Numbers - http://www.xtremedotnettalk.com/showthread.php?s=&threadid=49661&highlight=RichTextBox
Note: This answer is more to do with the abstract task of counting lines in a string, rather than to do with the GUI side of things. It's probably not as useful as some other answers for the original questioner, but I suspect it's useful in similar situations which don't involve GUIs. If enough people reckon it's not relevant here, I'll delete it.
I would use an existing type which already knows about line endings, namely TextReader, in conjunction with my LineReader type from MiscUtil:
string text = "ab\ncd";
int lines = new LineReader(() => new StringReader(text)).Count();
Alternatively, without the dependencies:
public IEnumerable<string> GetLines(string text)
{
using (TextReader reader = new StringReader(text))
{
string line;
while ((line = reader.ReadLine()) != null)
{
return line;
}
}
}
then:
int lineCount = GetLines(text).Count();
Note that this will count actual lines of text rather than line breaks - this may subtly different from what you want (e.g. it'll normally be line breaks + 1, but not if there's a line break at the end of the text).
public static int LineBreakCount(string s)
{
if (s == null) throw new ArgumentNullException("s");
return LineBreakCount(s, new[]{"\r\n", "\r", "\n"});
}
public static int LineBreakCount(string s, params string[] patterns)
{
if (s == null) throw new ArgumentNullException("s");
if (patterns == null) throw new ArgumentNullException("patterns");
return s.Split(patterns, StringSplitOptions.None).Length;
}
The order of the patterns in the first overload is important, because if you do "\r" or "\n" first, you'll wind up with almost or exactly twice as many items in the array, since it performs them in the order they're specified.