What about substring(0,10) or substring(0,11) depending on whether index 10 should inclusive or not? You'd have to check for length() >= index though.

An alternative would be org.apache.commons.lang.StringUtils.substring("your string", 0, 10);

Answer from Thomas on Stack Overflow
🌐
Briebug Blog
blog.briebug.com › blog › java-split-string
Using the Java String.split() Method
October 13, 2022 - These are the key points to remember about JavaString.split(): It is a convenient method, provided by the Java String class to split a String into an Array of Strings, given the passed delimiter.
Discussions

How can I split a String without using the Split method?
iterate through the String, when you reach a char that matches your split value take the string from a start position to your current position and store that in your array. Keep iterating until you reach a char that does not match your split value and set that position as your new start position.... More on reddit.com
🌐 r/javahelp
19
6
February 23, 2015
java - Split string by an index value (not middle of the word) - Stack Overflow
Trying to come up with method that will split the string based on the index value defined but if that index is in the middle of the word it will split it after the word. So if say the index is 31 , that would actually split the sentence like this (each line is 31 characters long) Java is a high-level programmin g language originally developed by Sun Microsystems and release d in 1995 · Notice how the word "programming" and "released" were split. If the character at ... More on stackoverflow.com
🌐 stackoverflow.com
January 26, 2022
Using charAt(index) method to split a String into an array.
You've got the right idea to use String.charAt(). That gives you a char. Is there any method in the Character class that could tell you if what you have is not a delimiter character? Once you have that you'll need some way to store these words. If the assignment specifies an array then you'll need to declare an array large enough to hold the words or dynamically resize the array as needed. One is certainly easier than the other. If you don't have to use an array then you might want to use some other sort of data structure. Have you learned about lists yet? More on reddit.com
🌐 r/javahelp
9
2
December 3, 2015
Index out of bounds
Index 1 out of bounds for length 1 Your array length is not 2 as you assume. The error clearly states that the length is 1. Always validate the real length before doing anything with array indexes. More on reddit.com
🌐 r/learnjava
13
1
August 22, 2018
Top answer
1 of 4
22

I've written a quick and dirty benchmark test for this. It compares 7 different methods, some of which require specific knowledge of the data being split.

For basic general purpose splitting, Guava Splitter is 3.5x faster than String#split() and I'd recommend using that. Stringtokenizer is slightly faster than that and splitting yourself with indexOf is twice as fast as again.

For the code and more info see https://web.archive.org/web/20210613074234/http://demeranville.com/battle-of-the-tokenizers-delimited-text-parser-performance (original link is dead and corresponding site does not appear to exist anymore)

2 of 4
6

As @Tom writes, an indexOf type approach is faster than String.split(), since the latter deals with regular expressions and has a lot of extra overhead for them.

However, one algorithm change that might give you a super speedup. Assuming that this Comparator is going to be used to sort your ~100,000 Strings, do not write the Comparator<String>. Because, in the course of your sort, the same String will likely be compared multiple times, so you will split it multiple times, etc...

Split all the Strings once into String[]s, and have a Comparator<String[]> sort the String[]. Then, at the end, you can combine them all together.

Alternatively, you could also use a Map to cache the String -> String[] or vice versa. e.g. (sketchy) Also note, you are trading memory for speed, hope you have lotsa RAM

HashMap<String, String[]> cache = new HashMap();

int compare(String s1, String s2) {
   String[] cached1 = cache.get(s1);
   if (cached1  == null) {
      cached1 = mySuperSplitter(s1):
      cache.put(s1, cached1);
   }
   String[] cached2 = cache.get(s2);
   if (cached2  == null) {
      cached2 = mySuperSplitter(s2):
      cache.put(s2, cached2);
   }

   return compareAsArrays(cached1, cached2);  // real comparison done here
}
🌐
GeeksforGeeks
geeksforgeeks.org › java › split-a-string-into-a-number-of-substrings-in-java
Split a String into a Number of Substrings in Java - GeeksforGeeks
July 23, 2025 - Let us consider a string which has n characters: 1. For each character at index i (0 to n-1): find substrings of length 1, 2, ..., n-i Example: Let our string be cat, here n = 3 (the length of string) here, index of 'c' is 0 index of 'a' is 1 index of 't' is 2 Loop from i = 0 to 2: (since n-1 = 2) When i = 0: Substring of length 1 : "c" Substring of length 2 : "ca" Substring of length 3 : "cat" , (substring of length n-i or 3-0 = 3) When i = 1: Substring of length 1 : "a" Substring of length 2 : "at" , (substring of length n-i or 3-1 = 2) When i = 2: Substring of length 1 : "t" , (substring of length n-i or 3-2 = 1) ... // Java Program to split a string into all possible // substrings excluding the string with 0 characters i.e.
🌐
W3Schools
w3schools.com › java › ref_string_split.asp
Java String split() Method
charAt() codePointAt() codePointBefore() codePointCount() compareTo() compareToIgnoreCase() concat() contains() contentEquals() copyValueOf() endsWith() equals() equalsIgnoreCase() format() getBytes() getChars() hashCode() indexOf() isEmpty() join() lastIndexOf() length() matches() offsetByCodePoints() regionMatches() replace() replaceAll() replaceFirst() split() startsWith() subSequence() substring() toCharArray() toLowerCase() toString() toUpperCase() trim() valueOf() Java Math Methods · abs() acos() addExact() asin() atan() atan2() cbrt() ceil() copySign() cos() cosh() decrementExact() exp
🌐
Medium
medium.com › @khalludi123 › using-javas-split-to-find-first-occurrence-5c09cb8cdf8a
Using Java’s .split() to Find First Occurrence | by Khalid Ali | Medium
May 6, 2020 - This feature of split() is very unintuitive and took me some time to figure out myself. There is probably a good reason for this feature, but I will take it for granted here. The only time this happens in the problem is when the String starts with the search term.
🌐
Baeldung
baeldung.com › home › java › java string › java string.split()
Java.String.split() | Baeldung
March 13, 2025 - A quick example and explanation of the split() API of the standard String class in Java.
Find elsewhere
🌐
Quora
quora.com › How-do-you-split-a-string-and-store-it-in-an-array-in-Java
How to split a string and store it in an array in Java - Quora
In java. lang. String. split(String regex, int limit) method splits this string around matches of the given regular expression. The array returned by this method contains each substring of...
🌐
Reddit
reddit.com › r/javahelp › how can i split a string without using the split method?
r/javahelp on Reddit: How can I split a String without using the Split method?
February 23, 2015 -

Hi,

I was wondering how I could take a string and split it into individual words and put those words back into a String array.

For example, the input "the quick brown fox jumped over the lazy dog" will be translated into the string array: {"the", "quick", "brown", "fox", "jumped", over", "the", "lazy", "dog"}

I can't use the split method for strings so I'm a bit stuck. I was prompted to declare a new string array with more entries than I will actually need, storing new words as I encounter space characters in this new array. Then, at the end, create a new String array with just enough entries, and copy over the non-null elements of the first array over.

I'm not sure how to implement that. Could I get some help on writing this method? Thanks in advance!

🌐
Sentry
sentry.io › sentry answers › java › how to split a string in java
How to split a string in Java | Sentry
May 15, 2023 - public class Main { public static void main(String[] arg) { String str = "how:to:split:a:string:in:java"; String[] arrOfStr = str.split(":"); for (String a : arrOfStr) { System.out.println(a); } } }
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › String › split
String.prototype.split() - JavaScript | MDN
The split() method of String values takes a pattern and divides this string into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and returns the array.
🌐
IronPDF
ironpdf.com › ironpdf for java › ironpdf for java blog › java pdf tools › string.split java
String.split Java (How It Works For Developers)
June 23, 2025 - The String.split() method in Java is a powerful tool that is used to split a string based on the string delimiters provided as parameter. When utilizing this method
🌐
Baeldung
baeldung.com › home › java › java string › split a string only on the first occurrence of delimiter
Split a String Only on the First Occurrence of Delimiter | Baeldung
August 7, 2025 - The split() instance method from the String class splits the string based on the provided regular expression. Moreover, we can use one of its overloaded variants to get the required first occurrence.
🌐
Javatpoint
javatpoint.com › java-string-split
Java String split() method - javatpoint
Java String split() method with method signature and examples of concat, compare, touppercase, tolowercase, trim, length, equals, split, string split in java etc.
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-index-split-and-manipulate-strings-in-javascript
How To Index, Split, and Manipulate Strings in JavaScript | DigitalOcean
August 24, 2021 - Now that we have a new array in the splitString variable, we can access each section with an index number. ... If an empty parameter is given, split() will create a comma-separated array with each character in the string. By splitting strings you can determine how many words are in a sentence, and use the method as a way to determine people’s first names and last names, for example. The JavaScript trim() method removes white space from both ends of a string, but not anywhere in between.
Top answer
1 of 2
1

This is a simple solution:

import java.util.*;

public class Main
{

  public static String[] splitBy(String text, int index)
  {
    int charIn = 0;
    String[] defaultArray = new String[2];

    for(charIn = index; charIn < text.length(); charIn++)
    {
      if(text.charAt(charIn) == ' ')
      {
        defaultArray[0] = text.substring(0, charIn);
        defaultArray[1] = text.substring(charIn, text.length() - 1);

        return defaultArray;
      }
    }

    return defaultArray;
  }
  public static void main(String[] args)
  {
    String text = "This is a nice text"; // Your text
    int index = 10; // Index to split

    System.out.println(splitBy(text, index)[0]); // Print first part of the splitted
    System.out.println(splitBy(text, index)[1]); // Print part 2
  }
}
2 of 2
0

Here is one way. No explicit loops involved.

  • find midpoint of string.
  • find first space after mid point.
  • find first space before mid point.
  • select split position based on distance from midpoint.
int mid = str.length()/2;
int indexBeyondMid = str.indexOf(' ',mid);
int indexBeforeMid = str.substring(0,mid).lastIndexOf(' ');
int splitPoint = mid - indexBeforeMid < indexBeyondMid - mid 
         ? indexBeforeMid 
         : indexBeyondMid;
String firstHalf = str.substring(0,splitPoint);
String secondHalf = str.substring(splitPoint+1); // ignores leading space.
System.out.println(firstHalf);
System.out.println(secondHalf);

The above will split as evenly as possible. If you want to just split on the first space after the mid point, then just split on indexBeyondMid and forget the rest.

If you want to split a line as optimally as possible to a specified linewidth, you can do it like this.

int lineWidth = 19;
while (!str.isBlank()) {
    lineWidth = lineWidth > str.length() ? str.length() : lineWidth;
    int indexBeyondMid = str.indexOf(' ',lineWidth);
    int indexBeforeMid = str.substring(0,lineWidth).lastIndexOf(' ');
    int splitPoint = lineWidth - indexBeforeMid < indexBeyondMid - lineWidth 
             ? indexBeforeMid 
             : indexBeyondMid;
    if (splitPoint < 0) {
        System.out.println(str);
        break;
    }
    System.out.println(str.substring(0, splitPoint));
    str = str.substring(splitPoint+1);
}

prints

Hey I am string that
will be split but
remember i will not
be cut in the middle
of the word
🌐
JavaRush
javarush.com › java blog › random en › split method in java: split string into parts
split method in java: split string into parts
October 8, 2023 - The first step is to split the string through the ";" character into its component parts. Then in each such part we will have information about a separate product, which we can process in the future. And then, within the framework of each product, we will separate the information using the "," symbol and take an element with a certain index (in which the price is stored) from the resulting array, convert it to a numerical form and make up the total cost of the order.
🌐
GeeksforGeeks
geeksforgeeks.org › java › split-string-java-examples
Java String split() Method - GeeksforGeeks
December 20, 2025 - split() method in Java is used to divide a string into an array of substrings based on a specified delimiter or regular expression.