0

In Java or Groovy is there a library or a simple implementation that for a text it would create substring at some length but not breaking a word in the middle?

An example method with an input: substring("My very long text", 9 /*substring length*/, true /*break on whole words only*/)

An output because without keeping the words it would result in My very l. Since I want to break on the whole words only it will be My very.

In case there are no spaces it would cut the string at the index:

substring("MyVeryLongText", 9 /*substring length*/, true /*break on whole words only*/) --> MyVeryLon

Amio.io
  • 20,677
  • 15
  • 82
  • 117
  • Related: http://stackoverflow.com/questions/34959014/java-string-break-by-space-after-position?noredirect=1&lq=1 – Thilo Sep 29 '16 at 06:22
  • Just to make sure: you want your substring to start from index 0? From the beginning of the string up to 4 chars or the first word boundary? – Wiktor Stribiżew Sep 29 '16 at 06:48
  • @WiktorStribiżew It was an example. I'll update the question to make it clearer. Thx for feedback! – Amio.io Sep 29 '16 at 06:55

1 Answers1

1

I believe I can say that there isn’t built into Java. We wrote our own method for a similar task. There could easily be some free library out there, but I don’t think I’d introduce a new dependency for this relatively simple problem. You will want to decide what you want to happen if there is no space at which to break (substring("Beginning with a long word", 4, true)). Maybe the library you find doesn’t do what you want in this case. If writing your own, you need to take the cases into account where the original string is too short (substring("Cat", 4, true)) and where the space comes right after the 4th char (substring("Long text", 4, true)).

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • I think what this means is that you start at your cutoff position, then search backwards for the preceding space, if there is none, fallback to cutting off right there or search forward until the next space. – Thilo Sep 29 '16 at 07:39