java-删除字符串的最后两个字符
这个问题已经在这里有了答案:
如何从字符串中删除最后一个字符? 29个答案
如何删除简单字符串的后两个字符05?
简单:
"apple car 05"
码
String[] lineSplitted = line.split(":");
String stopName = lineSplitted[0];
String stop = stopName.substring(0, stopName.length() - 1);
String stopEnd = stopName.substring(0, stop.length() - 1);
分割“:”之前的原始行
apple car 04:48 05:18 05:46 06:16 06:46 07:16 07:46 16:46 17:16 17:46 18:16 18:46 19:16
7个解决方案
83 votes
还减去-2或-3删除最后一个空格的基础。
public static void main(String[] args) {
String s = "apple car 05";
System.out.println(s.substring(0, s.length() - 2));
}
输出量
apple car
Ankur Singhal answered 2020-01-20T20:57:34Z
23 votes
使用String.substring(beginIndex,endIndex)
str.substring(0, str.length() - 2);
子字符串从指定的beginIndex开始,并扩展到索引(endIndex-1)处的字符。
Isuru Gunawardana answered 2020-01-20T20:57:58Z
4 votes
您可以使用以下方法删除最后的n字符-
public String removeLast(String s, int n) {
if (null != s && !s.isEmpty()) {
s = s.substring(0, s.length()-n);
}
return s;
}
masud.m answered 2020-01-20T20:58:18Z
1 votes
您可以使用substring函数:
s.substring(0,s.length() - 2));
对于第一个substring,您要对substring说,它必须从字符串的第一个字符开始,对于s.length() - 2,它必须在字符串结束之前完成2个字符。
有关substring函数的更多信息,请参见此处:
[http://docs.oracle.com/javase/7/docs/api/java/lang/String.html]
Francisco Romero answered 2020-01-20T20:58:52Z
1 votes
您也可以尝试以下代码进行异常处理。 在这里,您可以使用方法removeLast(String s, int n)(它实际上是masud.m的答案的修改版本)。 您必须为此功能提供String以及要从最后删除的char。 如果必须从最后删除的char数量大于给定的String长度,则会抛出StringIndexOutOfBoundException并显示自定义消息-
public String removeLast(String s, int n) throws StringIndexOutOfBoundsException{
int strLength = s.length();
if(n>strLength){
throw new StringIndexOutOfBoundsException("Number of character to remove from end is greater than the length of the string");
}
else if(null!=s && !s.isEmpty()){
s = s.substring(0, s.length()-n);
}
return s;
}
Razib answered 2020-01-20T20:59:12Z
0 votes
几乎是正确的,只是将您的最后一行更改为:
String stopEnd = stop.substring(0, stop.length() - 1); //replace stopName with stop.
要么
您可以替换最后两行;
String stopEnd = stopName.substring(0, stopName.length() - 2);
Saif answered 2020-01-20T20:59:41Z
0 votes
一种替代解决方案是使用某种regex:
例如:
String s = "apple car 04:48 05:18 05:46 06:16 06:46 07:16 07:46 16:46 17:16 17:46 18:16 18:46 19:16";
String results= s.replaceAll("[0-9]", "").replaceAll(" :", ""); //first removing all the numbers then remove space followed by :
System.out.println(results); // output 9
System.out.println(results.length());// output "apple car"
nafas answered 2020-01-20T21:00:05Z