40

I tried to search online to solve this question but I didn't found anything.

I wrote the following abstract code to explain what I'm asking:

String text = "how are you?";

String[] textArray= text.splitByNumber(4); //this method is what I'm asking
textArray[0]; //it contains "how "
textArray[1]; //it contains "are "
textArray[2]; //it contains "you?"

The method splitByNumber splits the string "text" every 4 characters. How I can create this method??

Many Thanks

Meroelyth
  • 5,310
  • 9
  • 42
  • 52

11 Answers11

79

I think that what he wants is to have a string split into substrings of size 4. Then I would do this in a loop:

List<String> strings = new ArrayList<String>();
int index = 0;
while (index < text.length()) {
    strings.add(text.substring(index, Math.min(index + 4,text.length())));
    index += 4;
}
Manuel Rauber
  • 1,583
  • 1
  • 17
  • 39
Guillaume Polet
  • 47,259
  • 4
  • 83
  • 117
  • This snippet is elegant, even contemplates the case in which there are remaining letters in the end of the text, it was very helpful – Ariel Sep 22 '20 at 19:43
36

Using Guava:

Iterable<String> result = Splitter.fixedLength(4).split("how are you?");
String[] parts = Iterables.toArray(result, String.class);
Pang
  • 9,564
  • 146
  • 81
  • 122
bruno conde
  • 47,767
  • 15
  • 98
  • 117
20

What about a regexp?

public static String[] splitByNumber(String str, int size) {
    return (size<1 || str==null) ? null : str.split("(?<=\\G.{"+size+"})");
}

See Split string to equal length substrings in Java

Community
  • 1
  • 1
Sampisa
  • 1,487
  • 2
  • 20
  • 28
3

Try this

 String text = "how are you?";
    String array[] = text.split(" ");

Or you can use it below

List<String> list= new ArrayList<String>();
int index = 0;
while (index<text.length()) {
    list.add(text.substring(index, Math.min(index+4,text.length()));
    index=index+4;
}
Suresh
  • 1,494
  • 3
  • 13
  • 14
3

Quick Hack

private String[] splitByNumber(String s, int size) {
    if(s == null || size <= 0)
        return null;
    int chunks = s.length() / size + ((s.length() % size > 0) ? 1 : 0);
    String[] arr = new String[chunks];
    for(int i = 0, j = 0, l = s.length(); i < l; i += size, j++)
        arr[j] = s.substring(i, Math.min(l, i + size));
    return arr;
}
st0le
  • 33,375
  • 8
  • 89
  • 89
3

Using simple java primitives and loops.

private static String[] splitByNumber(String text, int number) {

        int inLength = text.length();
        int arLength = inLength / number;
        int left=inLength%number;
        if(left>0){++arLength;}
        String ar[] = new String[arLength];
            String tempText=text;
            for (int x = 0; x < arLength; ++x) {

                if(tempText.length()>number){
                ar[x]=tempText.substring(0, number);
                tempText=tempText.substring(number);
                }else{
                    ar[x]=tempText;
                }

            }


        return ar;
    }

Usage : String ar[]=splitByNumber("nalaka", 2);

sampathpremarathna
  • 4,044
  • 5
  • 25
  • 37
2

I don't think there's an out-of-the-box solution, but I'd do something like this:

private String[] splitByNumber(String s, int chunkSize){
    int chunkCount = (s.length() / chunkSize) + (s.length() % chunkSize == 0 ? 0 : 1);
    String[] returnVal = new String[chunkCount];
    for(int i=0;i<chunkCount;i++){
        returnVal[i] = s.substring(i*chunkSize, Math.min((i+1)*chunkSize-1, s.length());
    }
    return returnVal;
}

Usage would be:

String[] textArray = splitByNumber(text, 4);

EDIT: the substring actually shouldn't surpass the string length.

Gilthans
  • 1,656
  • 1
  • 18
  • 23
1

Here's a succinct implementation using Java8 streams:

String text = "how are you?";
final AtomicInteger counter = new AtomicInteger(0);
Collection<String> strings = text.chars()
                                    .mapToObj(i -> String.valueOf((char)i) )
                                    .collect(Collectors.groupingBy(it -> counter.getAndIncrement() / 4
                                                                ,Collectors.joining()))
                                    .values();

Output:

[how , are , you?]
Pankaj Singhal
  • 15,283
  • 9
  • 47
  • 86
1

This is the simplest solution i could think off.. try this

public static String[] splitString(String str) {
    if(str == null) return null;

    List<String> list = new ArrayList<String>();
    for(int i=0;i < str.length();i=i+4){
        int endindex = Math.min(i+4,str.length());
        list.add(str.substring(i, endindex));
    }
  return list.toArray(new String[list.size()]);
}
dku.rajkumar
  • 18,414
  • 7
  • 41
  • 58
0

Try this solution,

public static String[]chunkStringByLength(String inputString, int numOfChar) {
    if (inputString == null || numOfChar <= 0)
        return null;
    else if (inputString.length() == numOfChar)
        return new String[]{
            inputString
        };

    int chunkLen = (int)Math.ceil(inputString.length() / numOfChar);
    String[]chunks = new String[chunkLen + 1];
    for (int i = 0; i <= chunkLen; i++) {
        int endLen = numOfChar;
        if (i == chunkLen) {
            endLen = inputString.length() % numOfChar;
        }
        chunks[i] = new String(inputString.getBytes(), i * numOfChar, endLen);
    }

    return chunks;
}
ibenjelloun
  • 7,425
  • 2
  • 29
  • 53
Mohamed kazzali
  • 33
  • 1
  • 10
0

My application uses text to speech! Here is my algorithm, to split by "dot" and conconate string if string length less then limit

String[] text = sentence.split("\\.");
 ArrayList<String> realText =  sentenceSplitterWithCount(text);

Function sentenceSplitterWithCount: (I concanate string lf less than 100 chars lenght, It depends on you)

private ArrayList<String> sentenceSplitterWithCount(String[] splittedWithDot){

        ArrayList<String> newArticleArray = new ArrayList<>();
        String item = "";
        for(String sentence : splittedWithDot){

            item += DataManager.setFirstCharCapitalize(sentence)+".";

            if(item.length() > 100){
                newArticleArray.add(item);
                item = "";
            }

        }

        for (String a : newArticleArray){
            Log.d("tts", a);

        }

        return newArticleArray;
    }

function setFirstCharCapitalize just capitalize First letter: I think, you dont need it, anyway

   public static String setFirstCharCapitalize(String input) {


        if(input.length()>2) {
            String k = checkStringStartWithSpace(input);
            input = k.substring(0, 1).toUpperCase() + k.substring(1).toLowerCase();
        }

        return input;
    }
Ucdemir
  • 2,852
  • 2
  • 26
  • 44