-8

I am having a string like this

String s1 = "2999.1049.00_GRB.1";
String s2 = "my File.txt.txt";

I want to replace the last ".1" with "_1" and ".txt" with "_txt"

The result of the String should be

s1 = "2999.1049.00_GRB_1" and s2 = "my File.txt_txt"

How can I do this. I am aware of replacing the first occurrence of the string. but don't know how to replace the last occurrence of a string.

Mehul Purohit
  • 71
  • 1
  • 8
  • Use lastIndexOf? – Ori Marko Aug 10 '17 at 12:41
  • 2
    This question doesn't demonstrate a whole lot of research on your part. – rmlan Aug 10 '17 at 12:41
  • 1
    Your question only contains requirements - it is not showing any efforts from your side to solve this problem yourself. Please add your attempts to this questions - as this site is not a free "we do your (home)work" service. Beyond that: please turn to the [help] to learn how/what to ask here. Thanks! – GhostCat Aug 10 '17 at 12:48
  • You can use `System.out.println("***"+s1.substring(0,s1.lastIndexOf(".")) +"_"+s1.substring(s1.lastIndexOf(".")+1));` It will work for both`s1` and `s2` – Om Sao Aug 10 '17 at 12:52
  • One more answer `class abc { public static void main(String[] args) { String s1= "2999.1049.00_GRB.1"; int i=s1.lastIndexOf("."); StringBuilder myName = new StringBuilder(s1); myName.setCharAt(i, '_'); System.out.println(myName); } }` By using `lastIndexOf` `.` and `replace` this index by `_` using `StringBuilder`. – Rohit-Pandey Aug 10 '17 at 12:56
  • Thank You @Rohit-Pandey. I got my solution – Mehul Purohit Aug 11 '17 at 08:13

2 Answers2

1

Simply use .replace with lastIndexOf method of string

System.out.println(s.replace(s.substring(s.lastIndexOf(".1"), s.length()), "_1"));
The N..
  • 70
  • 1
  • 5
0

You can use regex :

s = s.replaceAll("(.*)\\.(\\d+)$","$1_$2");  

//  (everything)point(digits) -> (everything)underscore(digits)

It will capture all element before the . in a group (group1), the digit(s) after in another group (group2), and replace by : group1_group2

  • the first group can be whatever you want
  • the second group is just digits, even more than 1

Regex demo

azro
  • 53,056
  • 7
  • 34
  • 70