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
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
Discussions

How to split a string in Java at a particular index? - Stack Overflow
I have a method that takes in a string. If it has three characters, then I put a : in between the zeroth and first element.Example: 123 → 1:23 If it has four characters, then I put a : in between the More on stackoverflow.com
🌐 stackoverflow.com
How can I split a String into two at a certain Index and keep both parts in Java? - Stack Overflow
I could split it twice with substring() and save both halves seperatly, but since I'm going for efficiency, I need a better solution which ideally saves both halves in a String[] in a single run. More on stackoverflow.com
🌐 stackoverflow.com
text - Splitting a string at a particular position in java - Stack Overflow
Your title talks about "at a particular position" but we don't know whether you know that position in terms of a character index or something else. ... If you want to put each pair of two words into a string, it might be easier simply to split it all by whitespace then iterate through and ... More on stackoverflow.com
🌐 stackoverflow.com
February 10, 2015
arrays - Java splitting string at index without cutting the word - Stack Overflow
I was just wondering it here is an API or some easy and quick way to split String at given index into String[] array but if there is a word at that index then put it to other String. So lets say I... More on stackoverflow.com
🌐 stackoverflow.com
September 19, 2018
🌐
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.
🌐
Medium
medium.com › @AlexanderObregon › splitting-a-word-into-two-parts-in-java-strings-c9d1aff469ac
Splitting a Word into Two Parts in Java Strings | Medium
August 22, 2025 - If a word is "Computer", choosing index 4 produces "Comp" as the first half and "uter" as the second. public class SplitDemo { public static void main(String[] args) { String word = "Computer"; int cut = 4; String left = word.substring(0, cut); ...
Find elsewhere
Top answer
1 of 2
1

Here's an old-fashioned, non-stream, non-regex solution:

public static List<String> chunk(String s, int limit) 
{
    List<String> parts = new ArrayList<String>();
    while(s.length() > limit)
    {
        int splitAt = limit-1;
        for(;splitAt>0 && !Character.isWhitespace(s.charAt(splitAt)); splitAt--);           
        if(splitAt == 0) 
            return parts; // can't be split
        parts.add(s.substring(0, splitAt));
        s = s.substring(splitAt+1);
    }
    parts.add(s);
    return parts;
}

This doesn't trim additional spaces either side of the split point. Also, if a string cannot be split, because it doesn't contain any whitespace in the first limit characters, then it gives up and returns the partial result.

Test:

public static void main(String[] args)
{
    String[] tests = {
            "This is a short string",
            "This sentence has a space at chr 36 so is a good test",
            "I often used to look out of the window, but I rarely do that anymore, even though I liked it",
            "I live in Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch",
    };

    int limit = 36;
    for(String s : tests)
    {
        List<String> chunks = chunk(s, limit);
        for(String st : chunks)
            System.out.println("|" + st + "|");
        System.out.println();
    }
}

Output:

|This is a short string|

|This sentence has a space at chr 36|
|so is a good test|

|I often used to look out of the|
|window, but I rarely do that|
|anymore, even though I liked it|

|I live in|
2 of 2
1

This matches between 1 and 30 characters repetitively (greedy) and requires a whitespace behind each match.

public static List<String> chunk(String s, int size) {
    List<String> chunks = new ArrayList<>(s.length()/size+1);
    Pattern pattern = Pattern.compile(".{1," + size + "}(=?\\s|$)");
    Matcher matcher = pattern.matcher(s);
    while (matcher.find()) {
        chunks.add(matcher.group());
    }
    return chunks;
}

Note that it doesn't work if there's a long string (>size) whitout whitespace.

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-string-java-examples
Java String split() Method - GeeksforGeeks
May 13, 2026 - Explanation: In this example, a string "Geeks for Geeks" is created and split using the split(" ") method, where a space is used as the delimiter. This divides the string into individual words and stores them in an array arr.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › String.html
String (Java Platform SE 8 )
April 21, 2026 - the array of strings computed by splitting this string around matches of the given regular expression ... Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter. ... String message = String.join("-", "Java", "is", "cool"); // message returned is: "Java-is-cool" Note that if an element is null, then "null" is added.
🌐
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 - In this tutorial, we’ll learn how to split a Java String only on the first occurrence of a delimiter using two approaches. Let’s say we have a text file having each line as a string made up of two parts – the left part indicating a person’s name and the right part indicating their greeting: Roberto "I wish you a bug-free day!" Daniele "Have a great day!" Jonas "Good bye!"
🌐
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 - In the dynamic world of Java programming, string manipulation is a fundamental skill that developers frequently employ for various tasks. The split() method, nestled within the java.lang.String class, stands out as a powerful tool for breaking down strings into substrings based on a specified delimiter.
🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › java › lang › String.html
String (Java Platform SE 7 )
Splits this string around matches of the given regular expression. The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string. The substrings in the array are in ...
🌐
W3Schools
w3schools.com › java › ref_string_split.asp
Java String split() Method
The split() method splits a string into an array of substrings using a regular expression as the separator. If a limit is specified, the returned array will not be longer than the limit.
🌐
Pass4sure
pass4sure.com › blog › mastering-string-splitting-in-java-extracting-the-final-element-with-precision-and-performance
Mastering String Splitting in Java: Extracting the Final Element with Precision and Performance – IT Exams Training – Pass4Sure
Extracting the final segment of a string after a split operation is a routine yet nuanced task in Java programming. The most straightforward method involves using the split() function and accessing the last array index.
🌐
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 - The first case of .split() is the most obvious. Given a sentence, “This rug is nice,” splitting on ‘rug’ would give a String array of [“This ”, “ is nice”]. So, we could calculate the index based on the first String.