Reputation: 44862
How would I split a string at a particular index? e.g split string at index 10, making the string now equal to everything up to index 10 and then dumping the remainder.
Upvotes: 26
Views: 167141
Reputation: 2064
this works too
String myString = "a long sentence that repeats itself = 1 and = 2 and = 3 again"
String removeFromThisPart = " and"
myString = myString .substring(0, myString .lastIndexOf( removeFromThisPart ));
System.out.println(myString);
the result should be
a long sentence that repeats itself = 1 and = 2
Upvotes: 2
Reputation: 63698
String s ="123456789abcdefgh";
String sub = s.substring(0, 10);
String remainder = s.substring(10);
Upvotes: 34
Reputation: 88737
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);
Upvotes: 40