0

I need to count the number of lines in a string (an address block). I think the easist thing to look for is a line feed character. So is there a way to count the number of line feed characters in a string?

Any help would be appreciated!

2
Contributors
1
Reply
12
Views
3 Years
Discussion Span
Last Post by SalmiSoft
0

String handling can vary enormously from one situation to another. Tell us some more about what you have tried, which compiler you are using, and the source of the data. Also how is the string declared? Is it simply a string, or an ANSIString, or WideString, or ...

You could step through the string character by character and count the line feeds. A simple loop from 1 to the string length would do that. Check if each character is chr(10) and if so, increment your line count.

If you wanted to get creative you could conjure up something using pos or posex in a loop, or use regular expressions. Create your own maintenance nightmare!

For a quick & easy solution in Delphi I might assign the string to the text property of a TStringList object, then simply read off the TStringList's Lines.Count property. Not efficient in terms of memory or speed but no thought is required and not much can go wrong.

You may need to give some thought to how you interpret edge conditions. If the string is empty is that zero lines or 1?
What if the last line does or doesn't end in a line feed?
What if an intermediate line is empty? Or successive lines are empty?

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.