用Java替换字符串中的最后一个字符 [英] Replacing last character in a String with java
本文介绍了用Java替换字符串中的最后一个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串:
String fieldName = "A=2,B=3 and C=3,";
现在我要用空格替换最后一个
.
Now I want to replace last ,
with space.
我用过:
if (fieldName.endsWith(",")) {
fieldName.replace(",", " ");
fieldName = fieldName.replace((char) (fieldName.length() - 1), 'r');
}
System.out.println("fieldName = " + fieldName);
但是我仍然得到相同的旧字符串.我该如何获取此输出呢?
But still I am getting the same old string. How I can get this output instead?
fieldName = A=2,B=3 and C=3
推荐答案
您可以简单地使用 substring
:
if(fieldName.endsWith(","))
{
fieldName = fieldName.substring(0,fieldName.length() - 1);
}
在执行 substring
后,确保将
查看全文