I have seven strings in a program named string1 through string7.
The size of each of the string will be 30 characters.
I will get a input string of unknown length.
I have to split this input string in 30 char strings and then set first substring into string1, 2nd in string2 and so on until possible. If input string is greater then 210 characters then remaining string at the end will be ignored.
How to handle the case when the input string is of size smaller then 210 char.
For e.g. 145 in which case string1 through string4 will be full and string5 will be made of remaining 15 char.
How to handle this nicely ?
I can do it reading char by char and putting first 30 char and string1, next in string2, etc until all char are consumed.
But is there a better way to do this ?
Since your Strings are not in an array or List you need to assign them explicitely.
Matcher m = Pattern.compile(".{1,30}").matcher(s);
String s1 = m.find() ? s.substring(m.start(), m.end()) : "";
String s2 = m.find() ? s.substring(m.start(), m.end()) : "";
String s3 = m.find() ? s.substring(m.start(), m.end()) : "";
String s4 = m.find() ? s.substring(m.start(), m.end()) : "";
String s5 = m.find() ? s.substring(m.start(), m.end()) : "";
String s6 = m.find() ? s.substring(m.start(), m.end()) : "";
String s7 = m.find() ? s.substring(m.start(), m.end()) : "";
Addendum as of 2025-02-28: Since some time Java features are extended. Using Streams a solution can now look like:
String inputString = "a"; // whatever
final int maxChunkLen = 30; // greater zero
final int maxNrRelevantChars = 210; // greater zero
StringBuilder buf = new StringBuilder();
inputString.substring(0, Math.min(inputString.length(), maxNrRelevantChars)).chars().forEachOrdered(
i -> {
buf.append(Character.toString(i));
if (buf.length() >= maxChunkLen) {
System.out.println(buf);
buf.delete(0, buf.length());
}
}
);
if (buf.length() > 0) {
System.out.println(buf);
buf.delete(0, buf.length());
}
To keep the String chunks for later use one may instance an String-Array or ArrayList and put the String-chunks into that instead of println them to console. Using an array the number of elements (array length) could be computed like
int relevantLen = Math.min(maxNrRelevantChars, s.length());
int arrayLen = Math.ceilDiv(relevantLen, maxChunkLen);