我有一个字符串:
String fieldName = "A=2,B=3 and C=3,";
现在我想用空格替换最后,
。
我用过:
if (fieldName.endsWith(",")) {
fieldName.replace(",", " ");
fieldName = fieldName.replace((char) (fieldName.length() - 1), 'r');
}
System.out.println("fieldName = " + fieldName);
但我仍然得到相同的旧字符串。我怎么能得到这个输出呢?
fieldName = A=2,B=3 and C=3
答案 0 :(得分:53)
您只需使用substring
:
if(fieldName.endsWith(","))
{
fieldName = fieldName.substring(0,fieldName.length() - 1);
}
确保在substring
作为Strings are immutable in java
答案 1 :(得分:9)
要获得所需的结果,您可以执行以下操作:
fieldName = fieldName.trim();
fieldName = fieldName.substring(0,fieldName.length() - 1);
答案 2 :(得分:8)
fieldName = fieldName.substring(0, string.length()-1) + " ";
答案 3 :(得分:5)
我想用空格
替换最后的','
if (fieldName.endsWith(",")) {
fieldName = fieldName.substring(0, fieldName.length() - 1) + " ";
}
如果你想删除尾随逗号,只需删除+ " "
。
答案 4 :(得分:4)
首先,字符串在java中是不可变的,你必须将replace的结果赋给变量。
fieldName = fieldName.replace("watever","");
您还可以使用String#replaceAll(regex, str)
;
fieldName = fieldName.replaceAll(",$","");
答案 5 :(得分:4)
试试这个:
s = s.replaceAll("[,]$", "");
答案 6 :(得分:2)
StringBuilder替换方法可用于替换最后一个字符。
StringBuilder.replace(startPosition, endPosition, newString)
StringBuilder builder = new StringBuilder(fieldName);
builder.replace(builder.length()-1, builder.length(), "");
builder.toString();
答案 7 :(得分:1)
您可以使用正则表达式来标识最后一个逗号(,)并将其替换为" "如下:
if(fieldName.endsWith(","))
{
fieldName = fieldName.replace(/,([^,]*)$/," ");
}
答案 8 :(得分:1)
if (fieldName.endsWith(",")) {
fieldName = fieldName.substring(0, fieldName.length()-1) + " ";
}
答案 9 :(得分:1)
org.apache.commons.lang3.StringUtils.removeEnd()和org.springframework.util.StringUtils.trimTrailingCharacter()是您的朋友:
StringUtils.removeEnd(null, *) = null StringUtils.removeEnd("", *) = "" StringUtils.removeEnd(*, null) = * StringUtils.removeEnd("www.domain.com", ".com.") = "www.domain.com" StringUtils.removeEnd("www.domain.com", ".com") = "www.domain" StringUtils.removeEnd("www.domain.com", "domain") = "www.domain.com" StringUtils.removeEnd("abc", "") = "abc"
@Test
public void springStringUtils() {
String url = "https://some.site/path/";
String result = org.springframework.util.StringUtils.trimTrailingCharacter(url, '/');
assertThat(result, equalTo("https://some.site/path"));
}
答案 10 :(得分:0)
@Abubakkar Rangara已经回答了解决问题的简单方法
替代方案是:
String[] result = null;
if(fieldName.endsWith(",")) {
String[] result = fieldName.split(",");
for(int i = 1; i < result.length - 1; i++) {
result[0] = result[0].concat(result[i]);
}
}
答案 11 :(得分:0)
您可以简单地使用:
if(fieldName.endsWith(","))
{
StringUtils.chop(fieldName);
}
来自commons-lang
答案 12 :(得分:-3)
将代码修改为fieldName = fieldName.replace(“,”,“”);