简体   繁体   中英

Java: How to split a string by a number of characters?

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

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;
}

Using Guava :

Iterable<String> result = Splitter.fixedLength(4).split("how are you?");
String[] parts = Iterables.toArray(result, String.class);

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

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;
}

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;
}

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);

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.

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?]

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()]);
}

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;
}

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;
    }

You can simply split the String into a String array via the following:

String[] parts = yourString.split(" ");
System.out.println(parts[0]);
System.out.println(parts[1]);
System.out.println(parts[2]);

output:

how
are
you?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM