java 如何在java中删除部分字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10024070/
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
How to remove part of the string in java?
提问by Poonam Hoshi
Possible Duplicate:
How do I split a string with any whitespace chars as delimiters?
可能的重复:
如何拆分带有任何空格字符作为分隔符的字符串?
I want to break up a string in java. I have a string "message.txt.cpabe".I want to remove the last portion and only want "message.txt". How do I do it?
我想在java中分解一个字符串。我有一个字符串“message.txt.cpabe”。我想删除最后一部分,只想要“message.txt”。我该怎么做?
回答by Eng.Fouad
String s = "message.txt.cpabe";
int indexOfLast = s.lastIndexOf(".");
String newString = s;
if(indexOfLast >= 0) newString = s.substring(0, indexOfLast);
System.out.println(newString); // prints "message.txt"
回答by Oleksi
I would use LastIndexOf(".")to get the index of that last '.', and then use substring()to cut out the part that you want.
我会使用LastIndexOf(".")来获取最后一个 '.' 的索引,然后使用substring()切出你想要的部分。
回答by ganesshkumar
String str="message.txt.cpabe";
str=str.substring(0,str.lastIndexOf("."));
Try this.
试试这个。
回答by jabal
Probably not what you wanted but certainly what you asked for.. :-)
可能不是您想要的,但肯定是您要求的.. :-)
String original = "message.txt.cpabe";
original = "message.txt";