I am writing a code to reshape the signals. I am getting the output with unwanted repetitions.
INPUT:
String[] rani = {"A","1","2","OK","B","3","4","OK","B","1","3","OK"};
Required OUTPUT:
A/3 B/7 B/4
Got OUTPUT:
A/3 A/3 A/3 A/3 B/7 B/7 B/7 B/7 B/4
ALGORITHM: Single alphabet strings ("A","B" etc.) are followed by number strings ("1","2" etc.). Each alphabet string is to be followed by slash and total of the numbers, and string "OK" is to ignored.
Being newcomer to java and programming I need help to get the needed output.
My code is:
public class SignalOK {
public static void main(String[] arg) {
String finalSignal = "";
String netSignal = "";
String name = "";
int total = 0;
String[] rani = { "A", "1", "2", "OK", "B", "3", "4", "OK", "B", "1",
"3", "OK" };
for (int i = 0; i < rani.length; i++) {
if ((rani[i] == "A") || (rani[i] == "B")) {
name = rani[i];
}
if ((rani[i] == "1") || (rani[i] == "2") || (rani[i] == "3")
|| (rani[i] == "4")) {
total = total + Integer.valueOf(rani[i]);
}
if (rani[i] == "OK") {
netSignal = name + "/" + String.valueOf(total) + " ";
name = "";
total = 0;
}
finalSignal = finalSignal + netSignal;
}
System.out.println(finalSignal);
}
}
Just move the final result string concatenation inside the "OK" if brackets:
if (rani[i].equals("OK")) {
netSignal = name + "/" + String.valueOf(total) + " ";
name = "";
total = 0;
finalSignal = finalSignal + netSignal;
}
Also, always use .equals() to compare strings.
A different approach :-
public static void main(String[] args) {
String[] inputString = {"A","1","2","OK","B","3","4","OK","B","1","3","OK"};
StringBuilder sb = new StringBuilder();
for(String s : inputString)
sb.append(s); // creating a String from array contents
String ss[] = sb.toString().split("OK"); // split on the basis of 'OK'
sb.setLength(0); // emptying the sb, so that it can be used later on also
for(String s : ss){
char[] ch = s.toCharArray();
sb.append(ch[0]); // first alphabet like 'A','B','C'
int val = 0;
for(int i = 1; i< ch.length ; i++)
val +=Integer.parseInt(""+ch[i]); // calculate the int value
sb.append("/"+val+" "); // finally appending alphabet with int value
}
System.out.println(sb);
}
Output :- A/3 B/7 B/4
Related
I have one requirement when i need to split the string by space and if word character length less than two characters than make it single word otherwise make it two words.
For more clear idea, here is what i want :
Input : This is car
Output : {"this is", "car"}
Input : a abcd xyz efg
Output : {"a abcd", "xyz", "efg"}
Input : a abcd xyz efg ha
Output : {"a abcd", "xyz", "efg ha"}
I have tried the following code but it is not working
String searchValue = "a abcd xyz efg ha"
String[] separated = searchValue.split(" ");
private List<String> getFinalSearchList(String[] separated) {
String resultString = "";
List<String> finalSearch = new ArrayList<String>();
for (String searchString : separated) {
if (searchString.length() > SEARCH_CHARACTOR_LENGTH) {
resultString = "";
resultString = resultString + searchString;
finalSearch.add(resultString);
} else if (searchString.length() <= SEARCH_CHARACTOR_LENGTH) {
finalSearch.remove(new String(resultString));
resultString = resultString + " " + searchString;
finalSearch.add(resultString);
}
}
return finalSearch;
}
Not a cleaner code but works as per requirement.
private List<String> getFinalSearchList(String[] separated) {
List<String> finalSearch = new ArrayList<>();
for (int index = 0; index < separated.length; index++) {
if (index == 0) {
finalSearch.add(separated[index]);
continue;
}
String previousString = finalSearch.get(finalSearch.size() - 1);
String searchString = separated[index];
if (searchString.length() <= SEARCH_CHARACTOR_LENGTH || previousString.length() <= SEARCH_CHARACTOR_LENGTH) {
finalSearch.remove(finalSearch.size() - 1);
finalSearch.add(String.join(" ", previousString, searchString));
} else {
finalSearch.add(searchString);
}
}
return finalSearch;
}
In the below implementation, I've modified your code to explicitly check the first 2 strings (if any) in the array.
Here is working code for the desired results:
static int SEARCH_CHARACTER_LENGTH = 2;
static String searchValue = "a abcd xyz efg ha";
static String[] separated = searchValue.split(" ");
private List<String> getFinalSearchList(String[] separated)
{
int i = 0;
String searchString = "";
String resultString = separated[0];
List<String> finalSearch = new ArrayList<String>();
if (separated[0].length() < SEARCH_CHARACTER_LENGTH && 1<separated.length)
{
resultString = separated[0]+ " " +separated[1];
finalSearch.add(resultString); i = 2;
}
else
{
finalSearch.add(separated[0]); i = 1;
}
for ( ; i<separated.length; i++)
{
searchString = separated[i];
if (searchString.length() > SEARCH_CHARACTER_LENGTH)
{
finalSearch.add(resultString = searchString);
}
else if (searchString.length() <= SEARCH_CHARACTER_LENGTH)
{
finalSearch.remove(new String(resultString));
resultString += " " + searchString;
finalSearch.add(resultString);
}
}
searchString = separated[separated.length-1];
return finalSearch;
}
Input: "This is car"
Output: [This is, car]
Input: "a abcd xyz efg ha"
Output: [a abcd, xyz, efg ha]
Input: "a abcd xyz efg a xyz pp ggg ha p p y"
Output: [a abcd, efg a, xyz, xyz pp, ggg ha p p y]
How do I write code so that if there two things are printed, there's an "and" between them and if it's the element being printed, it has an "and" like this:
"1 100 dollar bill and 2 200 dollar bills" "1 100 dollar bill, 2 200 dollar bills and 4 10 dollar bills"
public class kassa {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner pengarinput = new Scanner(System.in);
Scanner prisinput = new Scanner(System.in);
Scanner betalsumma = new Scanner(System.in);
int belopp, rest, summa, pris, v=0, antalsedlar=0, antalvarv=0;
String tu="tusenlapp", fh="femhundralapp", th="tvahundralapp", eh="enhundralapp",
ft="femtiolapp", tj="tjugolapp", ti="tiokronors mynt", f="femkronorsmynt", t="tvakronorsmynt",
et="enkronorsmynt";
String pengar [] = {tu, fh, th, eh, ft, tj, ti, f, t, et};
int sedlar[] = {1000, 500, 200, 100, 50, 20, 10, 5, 2, 1};
System.out.println("Hur mycket ska du betala i kontant?");
belopp = pengarinput.nextInt();
System.out.println("Hur mycket kostar varan?");
pris = prisinput.nextInt();
rest = belopp-pris;
while(rest>0) {
if(rest>=sedlar[v]) {
for(int i = 0; i<sedlar.length-1; i++) {
if(rest<sedlar[v]) {
antalsedlar=0;
v++;
}
while(rest>=sedlar[v]) {
antalsedlar++;
rest-=sedlar[v];
}
if(antalsedlar!=0) {
antalvarv++;
if(antalvarv!=0) {
if(antalsedlar==1 && sedlar[v]>=20) {
System.out.print(antalsedlar + " st " + pengar[v] + "ar " + ", ");
}
else {
System.out.print(antalsedlar + " st " + pengar[v] + " " + ", ");
}
}
}
}
}
else {
antalsedlar=0;
v++;
}
}
if(pris>belopp) {
System.out.println("Du har inte råd!");
}
}
}
Use a StringBuilder and basic conditions. In the following, we concatenate an array of Strings but you can generalize it to any type for which you can generate a String.
public String concat(String[] values) {
if (null == values) return "null";
if (values.length == 0) return "";
StringBuilder sb = new StringBuilder(values[0].trim());
for (int index = 1 ; index < values.length ; ++index) {
String op = index < (values.length - 1) ? ", " : " and ";
sb.append(op).append(values[index].trim());
}
return sb.toString();
}
Regardless to your code which is fairly hard to read and decipher, I provide you two ways to compose such sentence. Suppose there is an initial array, such as:
String[] array = {"1100 USD", "2200USD", "3300 USD", "4400 USD"};
Here you go, the solutions expect at least one item in the array:
Using StringBuilder and for-loop iteration:
StringBuilder sb = new StringBuilder(); // initialize StringBuilder
if (array.length == 1) { // special case of one element
sb.append(array[0]);
} else { // or 2+ elements
for (int i = 0; i < array.length - 1; i++) { // iterate all of them except the last one
sb.append(array[i]); // ... always append an item
if (i < array.length - 2) { // ... if is not the last one, append ','
sb.append(", ");
} else { // ... else append 'and' delimiter
sb.append(" and ");
}
}
sb.append(array[array.length - 1]); // finally append the remaining item
}
String sentence = sb.toString(); // composed sentence from StringBuilder
Using StringBuilder and String.join method:
StringBuilder sb = new StringBuilder(); // initialize StringBuilder
if (array.length == 1) { // special case of one element
sb.append(array[0]);
} else { // or 2+ elements
int len = array.length - 1; // length - 1
String[] noLastWord = Arrays.copyOfRange(array, 0, len); // array with no last word
String initialSentence = String.join(", ", noLastWord); // words connected with ','
sb.append(initialSentence) // composing the sentence
.append(" and ") // ... with 'and'
.append(array[array.length - 1]); // ... and the remaining word
}
String sentence = sb.toString(); // composed sentence
This can be packed to something more compact and readable:
StringBuilder sb = new StringBuilder();
if (array.length == 1) {
sb.append(array[0]);
} else {
String initialSentence = String.join(", ", Arrays.copyOfRange(array, 0, array.length - 1));
sb.append(initialSentence).append(" and ").append(array[array.length - 1]);
}
String sentence = sb.toString();
I'd like to get some help with coding that part when the program asks for inputs as many times as the length of the word.
So, when we start the program it picks a word randomly from the array and for example if the word that we're looking for is "team" that means we have four guesses.
I was trying to solve it with the snippet below. It seems so easy but I'm missing something:
while(!guess.equals(choosenWord) && letters <= choosenWord.length()) {
System.out.print("Your guess is: ");
guess = sc.nextLine();
The next part which I need some hint is if we have some matches in characters, than the found character should be displayed and "-" sign should be shown anywhere else: for example the word is still "team" that we're looking for and our guess is "baby" than "--a-" will be displayed.
Thank you for the advices.
import java.util.Scanner;
public class FindTheWord {
public static void main(String[] args) {
findTheWord();
}
public static void findTheWord() {
Scanner sc = new Scanner(System.in);
String[] words = {
"dog", "cat", "house", "love", "friend", "paper", "summer", "chips",
"number", "file", "program", "lotto", "work", "funny", "database",
"team", "profile", "facebook", "bean", "winter", "spring", "java",
"examination", "hospital", "birth", "baby", "newborn", "airplane",
"kindergarten", "autumn"};
int randomWord = (int) (Math.random() * 31);
String choosenWord = " ";
int letters = 0;
String guess = " ";
char ch = ' ';
for (int i = 0; i < words[randomWord].length(); i++) {
choosenWord = words[randomWord];
}
for (int j = 0; j < choosenWord.length(); j++) {
letters = choosenWord.length();
while(!guess.equals(choosenWord) && letters <= choosenWord.length()) {
System.out.print("Your guess is: ");
guess = sc.nextLine();
}
}
System.out.println(words[randomWord]);
System.out.println(letters);
}
}
Here's one solution with a ternary operator (? :):
...
guess = sc.nextLine();
for (char c : chosenWord.toCharArray()) {
System.out.print(guess.contains(String.valueOf(c)) ? c : '-');
}
...
Complete solution (Tested and verified), Just you need to run it.
public static void main(String[] args) {
findTheWord();
}
public static void findTheWord() {
//Init
Scanner sc = new Scanner(System.in);
String[] words = {
"dog", "cat", "house", "love", "friend", "paper", "summer", "chips",
"number", "file", "program", "lotto", "work", "funny", "database",
"team", "profile", "facebook", "bean", "winter", "spring", "java",
"examination", "hospital", "birth", "baby", "newborn", "airplane",
"kindergarten", "autumn"};
String randomWord = words[(int) (Math.random() * 31)];
String guess = "";
//Start Guessing
for (int i = 0; i <= randomWord.length(); i++) {
if (!guess.equals(randomWord)) {
System.out.print("Your guess is: ");
guess = sc.nextLine();
String result = checkGuessMatch(randomWord, guess);
if (!result.isEmpty())
System.out.println(result);
} else {
System.out.println("#################################");
System.out.println("############SUCCESS#############");
System.out.println("##########THE WORD WAS###" + guess);
System.out.println("#################################");
return;
}
}
System.out.println("####GAME OVER###");
System.out.println("THE WORD WAS = " + randomWord);
}
public static String checkGuessMatch(String word, String guess) {
Boolean sameIndexIsExist = false;
char[] wordChars = word.toCharArray();
char[] guessChars = guess.toCharArray();
String target = "";
for (int i = 0; (i < word.length()); i++) {
if (i < guess.length() && guessChars[i] == wordChars[i]) {
target = target + guessChars[i];
sameIndexIsExist = true;
} else
target = target + "-";
}
if (!sameIndexIsExist)
return "";
else return target;
}
The input is: i love cake
The output needs to be: Cake Love I
But the actual result is: I Love Cake
What I've got:
import java.util.regex.Pattern;
public class yellow {
static String reverseWords(String str){
Pattern pattern = Pattern.compile("\\s");
String[] temp = pattern.split(str);
String result = "";
for (int i = 0; i < temp.length; i++) {
if (i == temp.length - 1)
result = temp[i] + result;
else
result = " " + temp[i] + result;
}
return result;
}
public static void main(String[] args){
String source = "i love cake";
StringBuffer res = new StringBuffer();
String[] strArr = source.split(" ");
for (String str : strArr) {
char[] stringArray = str.trim().toCharArray();
stringArray[0] = Character.toUpperCase(stringArray[0]);
str = new String(stringArray);
res.append(str).append(" ");
}
System.out.print(res.toString());
}
}
What am I doing wrong?
for (String str : strArr) {
}
This loops forward. What you want is to loop backwards, or to place elements into the string backwards. I recommend you loop backwards and print as you go:
for (int i = strArr.length - 1; i >= 0; i--) {
char[] stringArray = strArr[i].trim().toCharArray();
stringArray[0] = Character.toUpperCase(stringArray[0]);
System.out.println(new String(stringArray));
}
Or, you could use that convenient reverseWords method that you never use anywhere... though looping backwards is faster. Probably.
[EDITED]
Call this for each line with string s, then print a line break (If you have multiple sentences & expect them in their own lines).
void reverseCamel(String s){
String[] ar = s.split("\\s+");
for(int i = ar.length - 1;i>=0;i--){
ar[i][0] = Character.toUpperCase(ar[i][0]);
System.out.print(ar[i] + " ");
}
}
Here is what i did.
public class Main {
public static void main(String[] args) {
reverse("I Love Cake");
}
public static void reverse( String string){
String[] word =string.split(" "); // split by spaces
int i = word.length-1;
while (i>=0){
// System.out.print(word[i].toUpperCase()+" ");//if you want in upper case
System.out.print(word[i]+" ");
i--;
}
}
}
First of all you have to reverse the String.
String[] words = source.split("\\s");
String reversedString = "";
for(int i = words.length -1; i>=0; i--){
reversedString += words[i] + " ";
}
Then, you know that the ASCII code of 'a' character is 97, 'A' is 65. To convert from lower case to capital you substract 32. All capitals are between 65 and 92. All small letters are between 97 and 124.
You want to capitalize only letters at the beginning of a word (preceded by a space or first letter).
String capitalCase = "";
for (int i = 0; i < reversedString.length(); i++) {
char c = reversedString.charAt(i);
if (c >= 97 && c <= 124) {
if (i == 0) c -= 32;
else if ((reversedString.charAt(i - 1) + "").equals(" ")) c -= 32;
}
capitalCase += c;
}
And here you go now System.out.println(capitalCase);
Overall, you will have the following code:
import java.util.Scanner;
public class yellow {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter a string:");
String source = s.nextLine();
String[] words = source.split("\\s");
String reversedString = "";
for (int i = words.length - 1; i >= 0; i--) {
reversedString += words[i] + " ";
}
String capitalCase = "";
for (int i = 0; i < reversedString.length(); i++) {
char c = reversedString.charAt(i);
if (c >= 97 && c <= 124) {
if (i == 0) c -= 32;
else if ((reversedString.charAt(i - 1) + "").equals(" ")) c -= 32;
}
capitalCase += c;
}
System.out.println(capitalCase);
}
}
Output:
Enter a string:
i love cake
Cake Love I
Java 8 * Apache Commons Lang
public static String reverseWordsInString(String str) {
List<String> words = Pattern.compile("\\s+").splitAsStream(str)
.map(StringUtils::capitalize)
.collect(LinkedList::new, LinkedList::addFirst, (a, b) -> a.addAll(0, b));
return words.stream().collect(Collectors.joining(StringUtils.SPACE));
}
Java 8
public static String reverseWordsInString(String str) {
List<String> words = Pattern.compile("\\s+").splitAsStream(str)
.map(word -> Character.toUpperCase(word.charAt(0)) + word.substring(1).toLowerCase())
.collect(LinkedList::new, LinkedList::addFirst, (a, b) -> a.addAll(0, b));
return words.stream().collect(Collectors.joining(" "));
}
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 ?
If you can use third-party libraries, with Guava this is just
Iterable<String> chunks = Splitter.fixedLength(30).split(string);
This can be converted to a List<String> with e.g. Lists.newArrayList.
(Disclosure: I contribute to Guava.)
private static Collection<String> splitStringBySize(String str, int size) {
ArrayList<String> split = new ArrayList<>();
for (int i = 0; i <= str.length() / size; i++) {
split.add(str.substring(i * size, Math.min((i + 1) * size, str.length())));
}
return split;
}
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()) : "";
How about using a char array for splitting the string, create a general-use method receiving the chunk size and maximum size to consider, and returning a String array?
public class SplitStringIntoFixedSizeChunks {
public static String[] Split(String text, int chunkSize, int maxLength) {
char[] data = text.toCharArray();
int len = Math.min(data.length,maxLength);
String[] result = new String[(len+chunkSize-1)/chunkSize];
int linha = 0;
for (int i=0; i < len; i+=chunkSize) {
result[linha] = new String(data, i, Math.min(chunkSize,len-i));
linha++;
}
return result;
}
public static void main(String[] args) {
String x = "flskdafsld~fdsakçkçfsda sfdaldsak~çfdskkfadsçlkçfldskçlflçfdskçldksçlkfdslçakafdslçdsklçfdskçlafdskçkdfsçlkfds~çlkfasdçlçfdls~kçlf~dksçlsakdçlkfç";
System.out.println("x length: "+x.length());
String[] lines = Split(x, 30, 210);
for (int i=0; i < lines.length; i++) {
System.out.println("lines["+i+"]: (len: "+lines[i].length()+") : "+lines[i]);
}
}
}
This example results:
x length: 145
lines[0]: (len: 30) : flskdafsld~fdsakçkçfsda sfdald
lines[1]: (len: 30) : sak~çfdskkfadsçlkçfldskçlflçfd
lines[2]: (len: 30) : skçldksçlkfdslçakafdslçdsklçfd
lines[3]: (len: 30) : skçlafdskçkdfsçlkfds~çlkfasdçl
lines[4]: (len: 25) : çfdls~kçlf~dksçlsakdçlkfç
This is something which should work:
String str = "11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111";
if (str.length() > 210)
{
str = str.substring(0, 209);
}
String newStr = str.replaceAll("(.{30})", "$1|");
System.out.println(newStr);
String[] newStrings = newStr.split("\\|");
What it does is that it takes the given string and at every 30 characters, it throws in a seperator. In this case, I am assuming that you have an idea of what will the user enter and what not so that you can throw in a seperator (or group of seperators) which the user will not enter. Once I do that, I split the string using the seperator I have just added.
This might help you.
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String st = br.readLine();
int len = st.length();
String[] str = new String[7];
len=len/30;
int i=0;
for(; i<7 && i<len; i++ ){
str[i] = st.substring(30*i, 30*(i+1));
System.out.println(str[i]);
}
if(i!=7){
str[i] = st.substring(30*i, st.length());
System.out.println(str[i]);
}
}
I ran into an issue with a specific usage of this technique. A user was copy/pasting M$ Word content into an HTML field that eventually was picked up by this technique to be split into multiple database fields.
The technique broke against M$ Word's use of carriage returns and other ASCII characters. The REGEX would split off each carriage return instead of a specified number of characters. To correct the issue, I modified Michael Besteck's code to the following:
Matcher m = Pattern.compile(".{1,30}", Pattern.DOTALL).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()) : "";
This accounts for the ASCII characters correctly.
This is what I did. Seems to work. Please comment if I am wrong anywhere:
package com.mypackage;
import java.util.ArrayList;
import java.util.List;
public class TestClass {
public static List<String> splitEqually(final String text, final int size) {
List<String> ret = new ArrayList<String>((text.length() + size - 1) / size);
for (int start = 0; start < text.length(); start += size) {
if (start + size > 0) {
String temp = text.substring(start, Math.min(text.length(), start + size));
int length = temp.length();
for (int i = 0; i < (size - length); i++) {
temp = temp + " ";
}
ret.add(temp);
} else {
ret.add(text.substring(start, Math.min(text.length(), start + size)));
}
}
return ret;
}
public static void main(final String args[]) {
String input = "hello wo";
String str1, str2, str3, str4, str5;
List<String> result = TestClass.splitEqually(input, 3);
try {
str1 = result.get(0);
System.out.println("1: " + result.get(0));
str2 = result.get(1);
System.out.println("2: " + result.get(1));
str3 = result.get(2);
System.out.println("3: " + result.get(2));
str4 = result.get(3);
System.out.println("4: " + result.get(3));
str5 = result.get(4);
System.out.println("5: " + result.get(4));
} catch (IndexOutOfBoundsException e) {
}
}
}
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
// your input
String input = "";
// strings 1-7 as array list
ArrayList<String> results = new ArrayList<String>();
int length;
if(input.length() > 210) {
length = 210;
} else {
length = input.length();
}
for(int i = 0; i <= length; i += 30) {
if((length - (i + 30)) > 0) {
results.add(input.substring(i, i + 30));
} else {
results.add(input.substring(i, length));
}
}
for(int a = 0; a < results.size(); a++) {
System.out.println("size: " + results.get(a).length() + " content: " + results.get(a));
}
}
}
private Collection<String> splitStringBySize(String strPrm, int sizePrm) {
ArrayList<String> splitLcl = new ArrayList<>();
int lLcl=strPrm.length();
int quantityLcl = lLcl / sizePrm;
for (int i = 0; i < quantityLcl; i++) {
splitLcl.add(strPrm.substring(i * sizePrm,(i+1) * sizePrm ));
}
int tailLcl = lLcl % sizePrm;
if(tailLcl>0){
splitLcl.add(strPrm.substring(lLcl-tailLcl,lLcl));
}
return splitLcl;
}
Using Streams, this one should do it in an easy way:
private static Stream<String> splitToFixedSize(String input, int maxSize) {
var noOfChunks = (int) Math.ceil((float) input.length() / maxSize);
return IntStream.range(0, noOfChunks).mapToObj(i -> {
var start = i * maxSize;
var end = Math.min((i + 1) * maxSize, input.length());
return input.substring(start, end);
});
}