2

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.

2
  • Do you want something like if(String.charAt(144) != ' ') return myString.split(" ")[0];? Commented Jul 23, 2016 at 10:35
  • if 144th character does not equal space then I want to read the string, I want to read the word completely and then break after the word.. Commented Jul 23, 2016 at 10:36

1 Answer 1

2

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...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.