梁航斌
梁航斌

Reputation: 83

How to get counts of characters on every line in TextView?

My TextView has multi-line text. And I want to get counts of characters every single line. I have tried String.split("\n"), but it didn't work...

Upvotes: 2

Views: 1058

Answers (3)

Umair Khalid
Umair Khalid

Reputation: 2329

You should create a function which store each line in different String variable and then count that string length.

Upvotes: 0

SilentKnight
SilentKnight

Reputation: 14021

Try this:

String[] lines = String.split(System.getProperty("line.separator"));
int[] counts = new int[lines.length];
for(int i = 0; i < lines.length; i++ ){
    String line= lines[i].replace(" ", "").trim();
    counts[i] = line.toCharArray().length;
}

Then you will get every line's counts of character even you just have one line or empty lines.

Upvotes: 0

Shadik Khan
Shadik Khan

Reputation: 1215

Try to splite by line using below code

String lines[] = String.split("\\r?\\n");

OR

String lines[] = String.split(System.getProperty("line.separator"));

and If you don’t want empty lines:

String lines[] = String.split("[\\r\\n]+")

Upvotes: 1

Related Questions