java 去掉字符串最后几个字符_java-删除字符串的最后两个字符

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值