Java:如何按字符数拆分字符串?

40

我尝试在网上寻找解决这个问题的方法,但没有找到任何东西。

我编写了以下抽象代码来解释我的问题:

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

方法splitByNumber将字符串"text"每4个字符分割一次。我该如何创建这个方法?

非常感谢


好奇一下,你使用这个的场景是什么? - Marcelo
可能与 https://dev59.com/S3E95IYBdhLWcg3wd9xK 重复。 - juergen d
可能是 Java中将字符串拆分为等长度的子字符串 的重复问题。 - Rumid
LeetCode许可证密钥格式化 - raikumardipak
12个回答

80

我认为他想要把一个字符串分成长度为4的子串。那么我会使用循环来实现:

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

这段代码非常优雅,甚至考虑了文本末尾仍有剩余字母的情况,非常有帮助。 - Ariel

36

使用Guava

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

20

3

试试这个

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

或者您可以在下面使用它。
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;
}

3

快速入门

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

3

使用简单的Java基元和循环。

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


2
我认为没有现成的解决方案,但我会像这样做:

我不认为有一个现成的解决方案,但我会这样做:

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

使用方法如下:

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

编辑:子字符串实际上不应超过字符串长度。


哎呀,假设 s.length() = 9,chunkSize = 4,你分配数组大小为 2,它应该是 3。 - st0le
你说得对,我已经修复了。一开始并不像我想象的那么优雅 :/ - Gilthans

1

这是我所能想到的最简单的解决方案.. 请尝试一下

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

1
这是一个使用Java8流的简洁实现:
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();

输出:

[how , are , you?]

0

我的应用程序使用文本转语音!这是我的算法,通过“点”进行拆分,并在字符串长度小于限制时连接字符串

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

函数 sentenceSplitterWithCount: (如果我连接的字符串长度小于100个字符,那就取决于你)

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

函数setFirstCharCapitalize只是将首字母大写:我认为你不需要它,无论如何。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接