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);
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);
String s ="123456789abcdefgh";
String sub = s.substring(0, 10);
String remainder = s.substring(10);
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
}
}
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
How to split a string in Java at a particular index? - Stack Overflow
How can I split a String into two at a certain Index and keep both parts in Java? - Stack Overflow
text - Splitting a string at a particular position in java - Stack Overflow
arrays - Java splitting string at index without cutting the word - Stack Overflow
Videos
You are close. You need to adjust the indicies for the substring calls:
private String addColon(String openOrclose)
{
String newHour = null;
if(openOrclose.length() == 3)
{
newHour = openOrclose.substring(0,1) + ":" + openOrclose.substring(1,3);
}
else
{
newHour = openOrclose.substring(0,2) + ":" + openOrclose.substring(2,4);
}
return newHour;
}
Your issue seems very much related to this question Insert a character in a string at a certain position
Note: I would have just commented this under your question but I have 49 reputation and need 1 more point to do so.
As @Jon Skeet already mentioned, you should really analyze the performance, because I can't imagine, that this is actually the bottleneck. However, another solution is splitting the String's char array:
String str = "Hello, World!";
int index = 4;
char[] chs = str.toCharArray();
String part1 = new String(chs, 0, index);
String part2 = new String(chs, index, chs.length - index);
System.out.println(str);
System.out.println(part1);
System.out.println(part2);
Prints:
Hello, World!
Hell
o, World!
This could be a general implementation:
public static String[] split(String str, int index) {
if (index < 0 || index >= str.length()) {
throw new IndexOutOfBoundsException("Invalid index: " + index);
}
char[] chs = str.toCharArray();
return new String[] { new String(chs, 0, index), new String(chs, index, chs.length - index) };
}
The problem with this approach is, it is less(!) efficient, than a simple
substring()call, because my code creates one more object than if you were using twosubstring()calls (the array is the additionally created object). In fact,substring()does exactly what I did in my code, without creating an array. The only difference is, that with callingsubstring()twice, the index is checked twice. Comparing that to object allocation costs is up to you.
Try stringName.split('*'), where * is what character you want to split the string at. It returns a String array.
I would use the String.substring(beginIndex, endIndex); and String.substring(beginIndex);
String a = "word1 word2 word3 word4";
int first = a.indexOf(" ");
int second = a.indexOf(" ", first + 1);
String b = a.substring(0,second);
String c = b.subString(second); // Only startindex, cuts at the end of the string
This would result in a = "word1 word2" and b = "word3 word4"
Do you want to do this in pairs always? This is a dynamic solution provided by the SO community wiki, Extracting pairs of words using String.split()
String input = "word1 word2 word3 word4";
String[] pairs = input.split("(?<!\\G\\w+)\\s");
System.out.println(Arrays.toString(pairs));
output:
[word1 word2, word3 word4]
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|
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.
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)
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
}
Try this,
String value = "FirstNameLastName yy-mm-ddAddress FirstNameLastName yy-mm-ddAddress FirstNameLastName yy-mm-ddAddress ";
for (int i = 0; i < value.length(); i++)
{
System.out.println("First Name : "+value.substring(i, i + 9));
System.out.println("Last Name : "+value.substring((i + 9), i + 18));
System.out.println("Date : "+value.substring(i + 18, i + 26));
System.out.println("Address : "+value.substring(i + 26, i + 56));
i = i + 55;
}
Knowing that each part is an exact length--and if it happens to be less, it's padded by spaces--this is a perfect situation for using String.substring(i,i) and String.trim().
For example: str.substring(0, 9) is the first nine characters. Now trim it, and any extra pad-spaces will be eliminated.