Java:如何用一些字符拆分字符串?

时间:2012-02-14 12:11:19

标签: java string split numbers character

我试图在线搜索以解决这个问题,但我没有找到任何东西。

我写了以下抽象代码来解释我在问什么:

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每4个字符拆分字符串“text”。我怎么能创建这个方法??

非常感谢

11 个答案:

答案 0 :(得分:58)

我认为他想要的是将一个字符串拆分为大小为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;
}

答案 1 :(得分:26)

使用Guava

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

答案 2 :(得分:9)

正则表达式怎么样?

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

请参阅Split string to equal length substrings in Java

答案 3 :(得分: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;
}

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

答案 5 :(得分: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;
    }

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

答案 6 :(得分: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);

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

答案 7 :(得分: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()]);
}

答案 8 :(得分:0)

试试这个解决方案,

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

答案 9 :(得分:0)

这是使用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?]

答案 10 :(得分:0)

我的应用程序使用文本进行语音转换! 这是我的算法,如果字符串长度小于限制,则用“点”分割并合并字符串

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

函数statementSplitterWithCount :(我将字符串lf长度限制在100个字符以内,具体取决于您)

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

函数setFirstCharCapitalize只是大写第一个字母:我想,您还是不需要它

function stringToUppercase(string) {
    const lowerCase = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
    const upperCase = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
    var newString = "";

    outer:
    for (var char = 0; char < string.length; char ++) {
        for (var letter = 0; letter < lowerCase.length; letter ++) {
            if (string[char] == lowerCase[letter]) {
                newString += upperCase[letter];
                continue outer;
            }
        }

        newString += string[char];
    }
    return newString;
}