Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split string at index

Tags:

java

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.

like image 958
Skizit Avatar asked Apr 11 '11 08:04

Skizit


4 Answers

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);

like image 194
Thomas Avatar answered Sep 29 '22 03:09

Thomas


String s ="123456789abcdefgh";
String sub = s.substring(0, 10);
String remainder = s.substring(10);
like image 21
Prince John Wesley Avatar answered Sep 29 '22 03:09

Prince John Wesley


String newString = oldString.substring(0, 10);
like image 37
WhiteFang34 Avatar answered Sep 29 '22 02:09

WhiteFang34


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

like image 44
Ar maj Avatar answered Sep 29 '22 03:09

Ar maj