简体   繁体   中英

How to get string length without counting newline characters as 2 chars in Java?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM