简体   繁体   中英

How to split a string into equal parts and store it in a string array

I'm fairly new to Java and am stuck on a particular homework question where a String gets passes and from there I have to split it into parts equal to an Integer that was passed.

For example: String "HelloWorld" is input and it has to be divided by 2 and those parts then have to be put into an array that has two parts like: array[hello, world].

Is there anyway to do this using a FOR loop?

My code so far enters the whole String into each array element. Here is my code:

String[] splitIntoParts(String word, int size) {

    String[] array = new String[size];     

    for (int i = 0; i < array.length; i++) {
        array[i] = word;
        println(array[i]);;
    }

    return array;
}

There are many ways:

Here's the regex version:

public void splitEqual(String s){
        int length = s.length();//Get string length
        int whereToSplit;//store where will split

            if(length%2==0) whereToSplit = length/2;//if length number is pair then it'll split equal
            else whereToSplit = (length+1)/2;//else the first value will have one char more than the other

        System.out.println(Arrays.toString(s.split("(?<=\\G.{"+whereToSplit+"})")));//split the string

    }

\\G is a zero-width assertion that matches the position where the previous match ended. If there was no previous match, it matches the beginning of the input, the same as \\A. The enclosing lookbehind matches the position that's four characters along from the end of the last match.

Both lookbehind and \\G are advanced regex features, not supported by all flavors. Furthermore, \\G is not implemented consistently across the flavors that do support it. This trick will work (for example) in Java, Perl, .NET and JGSoft, but not in PHP (PCRE), Ruby 1.9+ or TextMate (both Oniguruma).

Using Substring:

/**
     * Split String using substring, you'll have to tell where to split
     * @param src String to split
     * @param len where to split
     * @return 
     */
    public static String[] split(String src, int len) {
        String[] result = new String[(int)Math.ceil((double)src.length()/(double)len)];
        for (int i=0; i<result.length; i++)
            result[i] = src.substring(i*len, Math.min(src.length(), (i+1)*len));
        return result;
    }

You should also check this answer: Google Guava split

First check if the length of the string is a multiple of the divisor:

if(str.length() % divisor == 0) 

Then you know that you can grab equal chunks of it. So you use substring to pull them out, in a loop.

while(str.length() > 0) {
     String nextChunk = str.substring(0,divisor);
     // store the chunk. 

    str = str.substring(divisor,str.length());
} 

Will cycle through and grab a chunk that is divisor long each time.

You can use Brute force

public static List<String> splitStringEqually(String text, int size) 
{
    List<String> result = new ArrayList<String>((text.length() + size - 1) / size);
    for (int i = 0; i < text.length(); i += size) {
        result.add(text.substring(i, Math.min(text.length(), i + size)));
    }
    return result;
}
String s = "HelloWorld";
String firts_part=(String) s.subSequence(0, s.length() / 2);
String second_part=(String) s.subSequence((s.length() / 2)+1,s.length()-1 );

Try subSequence();

Since length of a string is dived by 2

Code :

        String st ="HelloWorld";
        String firstPart = "";
        String secondPart = "";
        for (int j = 0; j < st.length(); j++) {
            if ( j < st.length() /2) {
                firstPart += st.charAt(j);
            }else
                secondPart += st.charAt(j);
       }

        System.out.println(firstPart);
        System.out.println(secondPart);

Output :

Hello
World

Explanation : you add to firstPart String as long as your index has not met the middle index of the String. When it passed the middle index of String, you make the secondPart

This is not plagarism, formatted the answer mentioned here - https://stackoverflow.com/a/3761521 as per the question.

public static void main(String[] args){     
        String str = "HelloWorld";

        int parts = str.length()/3;

        System.out.println(Arrays.toString(
                str.split("(?<=\\G.{"+parts+"})")
            ));

    }

Try the following application.It is dividing the provided word into equal parts based on the provided size per part

public class WordSpliter {

  public static void main(String[] args) {
      String[] words = new WordSpliter().splitter("abcdefghij", 4);
      for(String s : words) System.out.println(s);
  }

  private String[] splitter(String word, int size) {
      // Decide the size of the String array 
      int rest = word.length() % size;
      int arrSize = ((word.length() - rest) / size) + 1;

      // Declare the array and the start point of the word
      String[] words = new String[arrSize];
      int startPoint = 0;

      for (int i = 0; i < words.length; i++) {
          if (i + 1 == words.length) {
              words[i] = word.substring(startPoint, startPoint + rest);
          } else {
              words[i] = word.substring(startPoint, startPoint +  4);
              startPoint += 4;
          }
      }
      return words;
  }

}

Good Luck !!!!

Just looking at your input HelloWorld , You are trying to substring your input by Upper case letter.

You should go with that.

String str = "HelloWorldUser";
List<Integer> indexList = new ArrayList<>();
for (int i = 0; i < str.length(); i++) {
    String temp = (str.charAt(i) + "").toUpperCase();
    if (temp.equals(str.charAt(i) + "")) { // check for upper case letters
       indexList.add(i);
      }
 }
List<String> subStrings = new LinkedList<>(); // to keep the insertion order
for (int i = indexList.size() - 1; i > -1; i--) { // substring reverse order
     subStrings.add(str.substring(indexList.get(i)));
     str=str.substring(0,indexList.get(i));
 }
Collections.reverse(subStrings); // reverse to get original order
System.out.println(subStrings);

Out put:

[Hello, World, User]

If you want to get final result in to an array you can use

String[] arr= subStrings.toArray(new String[subStrings.size()]);

I figured it out. Here is my code:

    String[] array = new String[size];
    char[] charArray = new char[length(word)];
    char[] temp = new char[length(word) / size];
    int place = 0;

    // turn the string into an array of chars
    for (int i = 0; i < charArray.length; i++) {
        charArray[i] = getChar(word, i);
    }

    // loop for each element of the desired string array
    for (int i = 0; i < array.length; i++) {

        // fill a temp array with the correct characters and the corect amount of characters
        for (int j = 0; j < charArray.length / size; j++) {                
            temp[j] = charArray[place];
            ++place;
        }

        // insert the temp array into each element of the string array
        array[i] = new String(temp);
    }

    return array;

A Simple solution is like

 static void split(String str, int n) {
    int partSize = str.length() / n;
    while (str.length() - partSize > 0) {
        String s = str.substring(0, partSize-1);
        System.out.print(s + " ");
        str = str.substring(partSize-1);
    }
    if (str.length() > 0) {
        System.out.print(str);
    }
}

You can do it using regex as follows:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        // Tests
        System.out.println(Arrays.toString(splitIntoParts("HelloWorld", 5)));
        System.out.println(Arrays.toString(splitIntoParts("HelloWorld", 4)));
        System.out.println(Arrays.toString(splitIntoParts("HelloWorld", 2)));
    }

    static String[] splitIntoParts(String word, int size) {
        return word.replaceAll("(.{" + size + "})", "$1\n").split("\n");
    }
}

Output:

[Hello, World]
[Hell, oWor, ld]
[He, ll, oW, or, ld]

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