Java:如何替换字符串中的最后一个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12832947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java : how to replace my last char in a string
提问by junaidp
I am trying to replace the last char in my String .
我正在尝试替换 String 中的最后一个字符。
String bowlNumber = 1.1;
bowlNumber.replace(bowlNumber.charAt(bowlNumber.length-1), 2);
By this I am able to replace my last character i.e 1 to 2.. but the problem is as my first character is also 1 , it also changes that to 2.
这样我就可以替换我的最后一个字符,即 1 到 2 .. 但问题是我的第一个字符也是 1 ,它也将其更改为 2。
What i want is to change 1.1 to 1.2 , but it makes 1.1 to 2.2
我想要的是将 1.1 更改为 1.2 ,但它使 1.1 为 2.2
Any idea?
任何的想法?
回答by Matei Suica
bowlNumber = bowlnNumber.substring(0,bowlNumber.length()-1) + "2";
回答by Arun Kumar
Try following code:
尝试以下代码:
String bowlNumber = "1.1";
bowlNumber=bowlNumber.substring(0, bowlNumber.length()-1)+"2";
System.out.println(bowlNumber);
Output
输出
1.2
1.2
回答by Subhrajyoti Majumder
String bowlNumber="1.1";
String replaceEnd = bowlNumber.replaceAll(".$", "2");
System.out.println(replaceEnd);
The OutPut is: 1.2
输出为:1.2