user3006193
user3006193

Reputation: 33

Remove characters after a certain string java

I'm new in java I have a problem. I have a string "x.y.z.k", and I want to create a new string "x.y.z." (so I want to remove all characters just after the last "."). I will appreciate it if somebody will help me.

Upvotes: 1

Views: 114

Answers (2)

user2591612
user2591612

Reputation:

String test = "x.y.z.k";
int lastPos = test.lastIndexOf('.');
String extractedString = test.substring(0, lastPos);

Outputs:

x.y.z

This code has been tested at compileonline.com

Upvotes: 0

Warlord
Warlord

Reputation: 2826

You can use String method .lastIndexOf() to get the last position of . and then use String method substring() to extract only the first part of the String, up to the . character.

Upvotes: 2

Related Questions