kodaek98 kodaek98 - 3 months ago 10
Java Question

How to change the dot (if more than 2) in java?

I'd like to change the dot to

""
if more than 2. So I mean that
hel.lo.txt
or
he.l.l.o.txt
then returns
hello.txt
.

I wrote this where not begin end with "."

int pointindex = filename.indexOf(".");
if (pointindex==0){
System.out.println("Point index :"+pointindex);
String mystring=filename.substring(pointindex, 1);
filename=filename.replace(mystring, "");
}

//end is "."
int extensions = filename.lastIndexOf(".");
String newfilename=filename.substring(extensions);
System.out.println(newfilename.length());
if ( newfilename.length()<2){
System.out.println("Dont have extension, so filename end is"+".");
int dotidx=filename.lastIndexOf(".");
filename=filename.substring(0,dotidx);
System.out.println(filename);
}

Answer

You can simply manipulate String here

String str = "he.l.l.o.txt";
int lastIndexOfDot = str.lastIndexOf('.');
String str1 = str.substring(0, lastIndexOfDot + 1);
String str2 = str.substring(lastIndexOfDot, str.length());
str = str1.replace(".", "") + str2;
System.out.println(str);

OUTPUT :

hello.txt

NOTE: You can create a method which take String as an argument and return the required String.