Keshav1234 Keshav1234 - 4 months ago 7
Android Question

how to perform intelligent string check in android

I have a long string text for example:

String2:

12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123


String3:

123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 234567890


I want to show first 144 characters in string and I need to show read more. If the 144th character is not equal to space as shown in string 3 then I need to check for space character after 144th character and then I need to break and show read more.

I am able to check whether 144th character is a space by using following code:

String.charAt(144) == ' ';


but if 144th character is not space then how can I wrap the string to break it when next space character is encountered.

Answer

You can use this code:

// String to be scanned to find the pattern.
String line = "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 234567890";
String pattern = "(.{144}[^ ]*).*";

// Create a Pattern object
Pattern r = Pattern.compile(pattern);

// Now create matcher object.
Matcher m = r.matcher(line);
if (m.find( )) {
 System.out.println(m.replaceAll("$1..."));
} else {
 System.out.println(line);
}

See demo.

It will split on the space after the 144th character of the string, no matter how far it is. With your example, the output is:

123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890...