java字符串截取

铁克禁卫军 2012-06-12 12:19:01
String path="翔安区\马巷镇\舫阳村\坪边\01_FWZDT.dwg" 我想把最后一个\后面的文件截掉,需要得到String path="翔安区\马巷镇\舫阳村\坪边\"
...全文
172 9 打赏 收藏 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
asdfgcjw 2012-06-13
  • 打赏
  • 举报
回复

String[] s=path.split("\\\\");
StringBuffer sb=new StringBuffer();
for(int i=0;i<s.length-1;i++){
if(i==(s.length-2)){
sb.append(s[i]);
}else{
sb.append(s[i]);
sb.append("\\");
}
}





jlu_lamp_lamp 2012-06-12
  • 打赏
  • 举报
回复
如果文件名固定的话可以用substring
要不然就用正则表达式里的group
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]

Java code
public static void main(){
String path="翔安区\\马巷镇\\舫阳村\\坪边\\01_FWZDT.dwg";
int index = path.lastIndexOf("\\");
System.out.println(index);
String newPath = pa……
[/Quote]
url得到最后一个\的位置(因为文件名是肯定没有\的)
然后用substring方法截取得到想要的字符串
ningtieming 2012-06-12
  • 打赏
  • 举报
回复
public static void main(){
String path="翔安区\\马巷镇\\舫阳村\\坪边\\01_FWZDT.dwg";
int index = path.lastIndexOf("\\");
System.out.println(index);
String newPath = path.substring(0,index+1);
System.out.println(newPath);
}
xlhb 2012-06-12
  • 打赏
  • 举报
回复
public static void main(){
String path="翔安区\\马巷镇\\舫阳村\\坪边\\01_FWZDT.dwg";
int index = path.lastIndexOf("\\");
System.out.println(index);
String newPath = path.substring(0,index+1);
System.out.println(newPath);
}
julianpzb 2012-06-12
  • 打赏
  • 举报
回复
嗯,一楼的方法可行。
a363722188 2012-06-12
  • 打赏
  • 举报
回复
嗯 一楼的写的不错呢!!
五哥 2012-06-12
  • 打赏
  • 举报
回复
的确 ,一楼的方法就可以 ,String.lastIndexOf("\\") ;
SpringHiSay 2012-06-12
  • 打赏
  • 举报
回复
public static void main(String[] args){
String path="翔安区\\马巷镇\\舫阳村\\坪边\\01_FWZDT.dwg";
int index = path.lastIndexOf("\\");
String newPath = path.substring(0,index+1);
System.out.println(newPath);
}
一楼写的不是可以吗,怎么还没结贴!

62,620

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧