How remove two character from a String?

NAI-PO-0009-1 this is original string. I need to remove -1, especially the last special char and the end char. I tried but could not get to remove two charecters from the end of the string.

Upvotes: 0

Views: 106

Answers (3)

Eduardo Soriano
Eduardo Soriano

Reputation: 192

Like @Darshan Lila said,

String test="NAI-PO-0009-1";
test=test.substring(0, test.length()-2);
System.out.println(test);

works for removing last two characters. If instead also need to remove the last special char and everything behind, you will have to use:

String test="NAI-PO-0009-1";
test=test.substring(0, test.lastIndexOf("-") -1); 
/*explain: second parameter of SubString() method is for the length of the resulting 
string, on a zero-based index, it has to end the last char before the last dash*/
System.out.println(test);

Hope it helps.

Upvotes: 0

No Idea For Name
No Idea For Name

Reputation: 11597

if you want to remove the last accorance of "-" til the end do:

String a="NAI-PO-0009-1";
System.out.println(a.substring(0, a.lastIndexOf('-'))-1);

if you just want to remove last to chars

System.out.println(a.substring(0, test.length()-2);

lastIndexOf finds and return the last appearance of a char.

substring return a sub string to the origin string begins with the character at the specified index and extends to the end of this string or up to endIndex - 1 if second argument is given.

Upvotes: 1

Darshan Lila
Darshan Lila

Reputation: 5868

Do following:

String test="NAI-PO-0009-1";
test=test.substring(0, test.length()-2);
System.out.println(test);

Output :

NAI-PO-0009

For more on such methods visit link.

Upvotes: 2

Related Questions