在本文中,我们将了解如何替换字符串中某个子字符串的最后一个实例作为典型需求。我们将在这篇文章中研究一个实用的 Java 解决方案。
替换 Java 中字符串中最后一次出现的子字符串:
我们可以使用lastIndexOf()方法来确定Java字符串中子字符串最后一次出现的位置,然后我们可以使用substring()方法来构建一个带有替换的新字符串。然后连接目标子字符串之前和之后的子字符串。
// Java Program Replace the last // Occurrence of a Substring in a String
// Driver Class public class ReplaceLastOccurrenceExample { public static String replaceLastOccurrence(String original, String target, String replacement) { int lastIndex = original.lastIndexOf(target);
if (lastIndex == -1) { // Target substring not found return original; }
String before = original.substring(0, lastIndex); String after = original.substring(lastIndex + target.length());
return before + replacement + after; }
// Main Function public static void main(String[] args) { String inputString = "Hello world, how's the world today?"; String targetSubstring = "world"; String replacementSubstring = "universe";
String result = replaceLastOccurrence(inputString, targetSubstring, replacementSubstring);
System.out.println("Original String: " + inputString); System.out.println("String after replacement: " + result); } }
|
上述程序的解释:
- ReplaceLastOccurrence 方法需要三个参数:原始字符串、必须更改的目标子字符串以及替换子字符串。
- 为了确定目标子字符串最后一次出现的位置,它使用lastIndexOf()。
- 如果无法找到所需的子字符串(lastIndex 为 -1),则原样返回原始文本。
- 然后使用 substring() 提取目标子字符串之前和之后的子字符串。
- 为了创建更新的字符串,它将这些子字符串与替换子字符串连接起来。