So I need the length of a string, but I want newline characters to be counter as 1 character in a string. Is there an elegant way to do this?
Asked
Active
Viewed 5,997 times
0
-
what you have tried? – Prashant Feb 19 '15 at 19:12
-
1Use `indexOf` repeatedly to count the number of `\r\n` occurrences? Or just replace `\r\n` with `\n` in the string and *then* use `length()`? That's slightly inefficient, but dead simple... – Jon Skeet Feb 19 '15 at 19:13
-
counting newline occurrences and subtracting that number from the length. that works, but I was just wondering if there is anything better – user3333414 Feb 19 '15 at 19:14
-
Newline characters *aren't* two chars. – user253751 Feb 20 '15 at 04:08
1 Answers
0
Count the number of characters in a string using string.length()
. Then subtract the number of times your 2-character newline occurs in the string. Have a look at Occurrences of substring in a string for nice ways of doing this.
There is no special method for doing this, because counting characters is much more complicated than it looks at first. For example, sometimes, the newline is not represented as \r\n
, but just as \n
- or just as \r
. In fact, you actually have no guarantee that something you think is a single character actually has a length of 1.
System.out.println("é".length());
This prints 2, because I used an e
followed by a character called a combining acute accent.