How to Split Fixed Size with Java
Splitting a Java String into a series of smaller Strings with a fixed width is helpful when you need to copy the data to a source that has limited space, such as a table with a specific column width. A Java String is an object that contains a series of characters, such as a name or a sentence from a book. Splitting up a String is done by looping through the String, repeatedly calling the "substr" function and storing the new list of Strings.
Instructions
-
-
1
Open your Java file in an editor such as Netbeans, Eclipse or JBuilder X.
-
2
Create a function to split a String into smaller Strings of a fixed size by adding the following code in your file:
public static List<String> split_str_fixed_size(String str, int fixed_size)
{
int pos = 0;
String tmp = "";
List<String> ret_value = new ArrayList<String>((str.length() + fixed_size - 1) / fixed_size);
for (pos = 0; pos < str.length(); pos += fixed_size)
{
tmp = str.substring(pos, Math.min(str.length(), pos + fixed_size));
ret_value.add(tmp);
}
return ret_value;
}
The function creates a "List" of Strings that have the specified fixed size. It then loops through the String, calling the "substring" function to copy fixed size sections of the String into the "List."
-
-
3
Call the "split_str_fixed_size" function to split your String into fixed size parts by adding the following code in another function:
String str = "example string of characters";
int fixed_size = 3;
List<String> str_split = new ArrayList<String>();
str_split = split_str_fixed_size(str,3);
The "str_split" will contain the Strings "exam", "ple ", "stri", "ng o", "f ch", "arac" and "ters."
-
4
Save the Java file, compile and run your program to split up the String.
-
1