Lets say I have a string of abcd
. How do I write a method which will transform that string into abc.d
? Or is there any method available implementation out there ?
What I have tried so far
int dotPlacing = propertyName.lastIndexOf(".");//12
String modString = propertyName.replace(".", "");
modString = modString.substring(0, dotPlacing-1) + "."+modString.substring(dotPlacing-1);
I am using that for writing Hibernate criteria. It works for user.country.name
but not for user.country.name.ss
. Havent tried for any other strings.
You can extract substring form 0 to lastIndexOf('.')
. In this substring replace all .
to empty string. After that merge with subtring (from lastIndexOf .
to end).
Something like:
String theString = "a.b.c.d";
String separator = ".";
String replacement = "";
String newString = theString.substring(0, theString.lastIndexOf(separator)).replaceAll(separator , replacement).concat(theString.substring(theString.lastIndexOf(separator)));
Assert.assertEquals("abc.d", newString);
String start = "a.b.c.d.wea.s";
String regex = "\\.(?=.*\\.)";
String end = start.replaceAll(regex, "");
System.out.println(end);
You are using dotPlacing
not on your original string but on new string that doesn't have any dots so its length has changes, which is main reason of your problems.
Change your code to
int dotPlacing = propertyName.lastIndexOf('.');
String modString = propertyName.substring(0, dotPlacing).replace(".","")
+ propertyName.substring(dotPlacing);
System.out.println(modString);
Use StringTokenizer
String in = "a.b.c.d";
StringTokenizer t = new StringTokenizer(in,".");
String last = "",result = "";
while(t.hasMoreTokens())
{
last = t.nextToken();
result += " "+last;
}
result = result.trim();
result.replaceAll(last,"."+last);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.