假设我有一串 a.b.c.d
。如何编写一个将该字符串转换为 abc.d
的方法?或者是否有任何可用的实现方法?
到目前为止我尝试了什么
int dotPlacing = propertyName.lastIndexOf(".");//12
String modString = propertyName.replace(".", "");
modString = modString.substring(0, dotPlacing-1) + "."+modString.substring(dotPlacing-1);
我正在使用它来编写 Hibernate 标准。它适用于 user.country.name
但不适用于 user.country.name.ss
。还没有尝试过任何其他字符串。
最佳答案
您可以将子字符串从 0 提取到 lastIndexOf('.')
。在此子字符串中将所有 .
替换为空字符串。之后与 subtring 合并(从 lastIndexOf .
到结束)。
类似于:
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);
关于java - 替换除最后一次出现的每个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19817884/