简体   繁体   English

如何在Java中删除子字符串

[英]How to remove a substring in java

I am receiving a file path with "xyz" appended to it. 我收到一个附加了“ xyz”的文件路径。 name would look like D:/sdcard/filename.docxyz 名称看起来像D:/sdcard/filename.docxyz

i am using the below code to remove xyz but it is not working. 我正在使用以下代码删除xyz,但无法正常工作。 what is missing here ? 这里缺少什么?

    String fileExtension = path.substring(path.lastIndexOf(".")+1);

    String newExtension= fileExtension;

    newExtension.replace("xyz", "");

    path.replace(fileExtension, newExtension);

    return path;

What is missing is that you need to save the result of your operations. 缺少的是您需要保存操作结果。 Strings are immutable in Java, and the results of all String manipulations are therefore returned in the form of a new String : 字符串在Java中是不可变的,因此所有String操作的结果都以新String的形式返回:

newExtension = newExtension.replace("xyz", "");
path = path.replace(fileExtension, newExtension);

Java中的String是不可变的,对其进行的更改永远不会发生,但是每次返回新的字符串时,

newExtension  = newExtension.replace("xyz", "");

You could also use replaceAll() with a regex. 您还可以使用带有正则表达式的replaceAll()。

public static void main(String[] args) {
    String s = "D:/sdcard/filename.docxyz";
    System.out.println(s.replaceAll("xyz$", "")); // $ checks only the end

}

O/P : O / P:

 input : s = "D:/sdcard/filename.docxyz";
 D:/sdcard/filename.doc 


 input : String s = "D:/sdcard/filenamexyz.docxyz";
 output : D:/sdcard/filenamexyz.doc
newExtension.replace("xyz", ""); 

Will only return string which has "xyz" removed but newExtension will remain as it is. 将仅返回已删除“ xyz”的字符串,但newExtension将保持原样。 Simple fix for your problem is use as below 解决问题的简单方法如下

String newExtension= fileExtension.replace("xyz", "");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM