I'm having a string as following in Java. The length of the string is not known and as an example it will be something like below.
String str = "I love programming. I'm currently working with Java and C++." For some requirement I want to get first 15 characters. Then 30, 45, 70 next characters. Once the string was split if the name was not meaningful then it should be split from nearest space. For the above example output is as following.
String strSpli1 = "I love "; //Since 'programming' is splitting it was sent to next split String strSpli2 = "programming. I'm currently ";//Since 'working' is splitting it was sent to next split String strSpli3 = "working with Java and C++."; Please help me to achieve this.
Updated answer for anybody having this kind of requirement.
String str = "I love programming. I'm currently working with Java and C++."; String strSpli1 = ""; String strSpli2 = ""; String strSpli3 = ""; try { strSpli1 = str.substring(15); int pos = str.lastIndexOf(" ", 16); if (pos == -1) { pos = 15; } strSpli1 = str.substring(0, pos); str = str.substring(pos); try { strSpli2 = str.substring(45); int pos1 = str.lastIndexOf(" ", 46); if (pos1 == -1) { pos1 = 45; } strSpli2 = str.substring(0, pos1); str = str.substring(pos1); try { strSpli3 = str.substring(70); int pos2 = str.lastIndexOf(" ", 71); if (pos2 == -1) { pos2 = 45; } strSpli3 = str.substring(0, pos2); str = str.substring(pos2); } catch (Exception ex) { strSpli3 = str; } } catch (Exception ex) { strSpli2 = str; } } catch (Exception ex) { strSpli1 = str; } Thank you
indexOfmethod of String class to find the nextspacecharacters that are near to yourlengthof 30,45,70 and split the string usingsubstring.30. Then check this substring that you have split if it is breaking a word in the middle. If it is breaking the word, then find the two nearest ` ` in your string usingindexOf. Once you have those 2 indices, you can decide which one to choose and update your new substring. Then you can proceed to the nextlengthyou want and repeat the same process until you reach the end of the string.