Skizit
Skizit

Reputation: 44862

split string at index

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

Answers (5)

Ar maj
Ar maj

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

Prince John Wesley
Prince John Wesley

Reputation: 63698

String s ="123456789abcdefgh";
String sub = s.substring(0, 10);
String remainder = s.substring(10);

Upvotes: 34

WhiteFang34
WhiteFang34

Reputation: 72049

String newString = oldString.substring(0, 10);

Upvotes: 2

MByD
MByD

Reputation: 137382

This should do it:s = s.substring(0,10);

Upvotes: 1

Thomas
Thomas

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

Related Questions