在 Java 中替换字符串指定索引处的字符

本文将介绍在 Java 中,我们如何替换字符串中特定索引的字符。我们可以使用不同的方法来实现我们的目标,在下面的例子中提到。

在 Java 中使用 substring() 替换字符串索引处的字符

在我们的第一个例子中,我们有一个字符串-ab,其中有一个字符 A,这是一个大写字母,不符合句子的要求,我们想用一个小写字符 a 来替换它。

为了替换它,我们使用 String 类的 substring() 函数,它以一个范围或字符串的起始索引作为参数。我们的目标字符位于索引 8 的位置。

ab.substring(0, index) 返回字符串从 0 到第 8 位的部分。我们将这部分字符串与我们的新字符 a 连接起来,并使用 ab.substring(index + 1) 连接剩余的字符串。

public class ReplaceCharAtIndex {
    public static void main(String[] args) {
        String ab = "This is A String";
        int index = 8;
        String newString = ab.substring(0, index) + 'a'+ ab.substring(index + 1);
        System.out.println(newString);
    }
}

输出:

This is a String

在 Java 中使用 StringBuilder() 替换字符串指定索引处的字符

我们有与前一个例子中使用的相同的字符串,但将使用 StringBuilder() 来创建一个新的可修改的字符串,因为在 Java 中,一个普通的字符串是不可改变的。由于 newString 现在是可修改的,我们可以使用它的 setChartAt() 方法将一个新的 char 设置为一个位置或索引。

newString.setCharAt(8, 'a') 将字符 a 设置在第 8 位。

public class ReplaceCharAtIndex {
    public static void main(String[] args) {
        String ab = "This is A String";
        StringBuilder newString = new StringBuilder(ab);
        newString.setCharAt(8, 'a');
        System.out.println(newString);
    }
}

输出:

This is a String

在 Java 中将字符串转换为字符数组以替换字符串指定索引处的字符

最后一个方法是使用 toCharArray() 将字符串 oldString 转换为 char 的数组。我们可以通过指定其位置来替换数组中的任何值。

我们可以看到,在 oldString 中有一个错别字,我们需要用字符( n )替换字符( m )。我们可以使用 charArray[index] = 'n'来替换我们在索引处的字符。

最后,我们必须使用 String.valueOf()char[] 转换为字符串。输出显示该字符已被替换。

public class ReplaceCharAtIndex {
    public static void main(String[] args) {
        String oldString = "This is an example strimg";
        int index = 23;
        char[] charArray = oldString.toCharArray();
        charArray[index] = 'n';
        String newString = String.valueOf(charArray);
        System.out.println(newString);
    }
}

输出:

This is an example string

在 Java 中替换字符串中的字符

在本教程中,我们将介绍两个方法,replace()replaceFirst()String 类,在 Java 中替换给定字符串中的一个或多个字符。

String.replace() 替换 Java 字符串中的单个字符

我们可以使用 replace() 方法来替换字符串中的单个字符。replace(oldChar, newChar) 要求两个参数:第一个参数是我们要替换的字符,第二个参数是要替换旧字符的新字符。

在下面的例子中,我们有一个字符串 oldString1,其中包含了一个带有&的语句,但我们想用逗号 , 来替换它。这可以通过使用 oldString1 调用 replace() 方法并传递&, 来简单实现。

需要注意的是,在 replace() 中,& 符前有空格。这是因为我们的目标字符周围有空格。为了消除空格,我们将用逗号来替换&和空白。

public class ReplaceCharString {
    public static void main(String[] args) {
        String oldString1 = "My name is Sam & I am a software developer.";
        String newString1 = oldString1.replace(" &", ",");
        System.out.println(newString1);
    }
}

输出:

My name is Sam, I am a software developer.

String.replaceFirst() 仅替换 Java 字符串中第一次出现的字符

在一个字符串中,我们想要替换的同一个字符可能会出现不止一次。如果我们只想替换第一次出现的字符,而忽略之后出现的其他字符,那么就可以使用 String 类的另一个方法,即 replaceFirst()。顾名思义,它只替换字符串的第一个字符。

在这个例子中,我们有一个有两个&的字符串,我们只想像前面的例子一样,用逗号替换第一个&,而忽略第二个&。因此,我们使用 oldString.replaceFirst(oldChar, newChar) 来传递空格和一个逗号。输出显示了最终的结果。

public class ReplaceCharString {
    public static void main(String[] args) {
        String oldString1 = "I have used multiple Internet providers & but my current provider is AT&T.";
        String newString1 = oldString1.replaceFirst(" &", ",");
        System.out.println(newString1);
    }
}

输出:

I have used multiple Internet providerss, but my current provider is AT&T.

Java 中使用 String.replace() 替换一个字符串中的两个字符

在本教程的最后一个例子中,我们将使用 replace() 来替换两个不同的字符。在 oldString1 中,我们要用一个小字母字符(v)替换大写字母字符(V),并且将要字符串的最后一个字符,逗号 , 替换为 .

我们可以通过连接两个 replace() 方法,然后传递正确的字符,在一行中完成。

public class ReplaceCharString {
    public static void main(String[] args) {
        String oldString1 = "My name is Sam and I am a Software DeVeloper,";
        String newString1 = oldString1.replace("V", "v").replace(",", ".");
        System.out.println(newString1);
    }
}

输出:

My name is Sam and I am a Software Developer.

在 Java 中替换字符串中的多个字符

String.replaceAll()String.replace() 是 Java 中替换字符串中字符的两个有用方法。在本文中,我们将看到如何使用这两种方法来替换字符串中的多个字符。

replaceAll() 可以使用正则表达式来完成这个任务,但如果我们不想使用正则表达式,我们可以使用 replace() 方法。

在 Java 中使用 replaceAll() 替换字符串中的多个字符

replaceAll() 用于当我们想要替换所有指定字符时。我们可以使用正则表达式来指定要替换的字符。这个方法需要两个参数,第一个是正则表达式模式,第二个是我们要放置的字符。

在下面的例子中,我们将使用一些常见的正则表达式来替换多个字符。

public class ReplaceAllChars {
    public static void main(String[] args) {
        String stringUnderscoresForward = "j_u_s_t_a_s/t/r/i/n/g";
        String stringWithDigits = "abcd12345efgh";
        String stringWithWhiteSpaces = "s t r i n g";
        String stringWithLowerCase = "This is a Lower Case String";
        String finalString1 = stringUnderscoresForward.replaceAll("[_/]", "-");
        String finalString2 = stringWithDigits.replaceAll("[\\d]", "");
        String finalString3 = stringWithWhiteSpaces.replaceAll("[ ]", "");
        String finalString4 = stringWithWhiteSpaces.replaceAll("[\\s]", "-");
        String finalString5 = stringWithLowerCase.replaceAll("[\\p{Lower}]", "");
        System.out.println("Old String: "+stringUnderscoresForward+" New String: "+finalString1);
        System.out.println("Old String: "+stringWithDigits+" New String: "+finalString2);
        System.out.println("Old String: "+stringWithWhiteSpaces+" New String: "+finalString3);
        System.out.println("Old String: "+stringWithLowerCase+" New String: "+finalString4);
        System.out.println("Old String: "+stringWithLowerCase+" New String: "+finalString5);
    }
}

输出:

Old String: j_u_s_t_a_s/t/r/i/n/g --New String: j-u-s-t-a-s-t-r-i-n-g
Old String: abcd12345efgh --New String: abcdefgh
Old String: s t r i n g --New String: string
Old String: This is a Lower Case String --New String: s-t-r-i-n-g
Old String: This is a Lower Case String --New String: T   L C S

在上面的例子中,我们使用了多个常用的正则表达式。让我们看看它们的含义和工作原理。

stringUnderscoresForward 中的每一个字符都由下划线和斜线分隔,我们将用破折号(-)替换所有的字符。[char1 char2] 是用来用一个字符替换两个字符的正则表达式。我们可以使用 [_/] 来替换所有的下划线和斜线。

stringWithDigits 是一个包含随机字母和它们之间的一些数字的字符串。我们希望用一个空字符替换每一个数字。要做到这一点,我们可以使用/d 转义序列来转义数字。[\d] 将被用作一个正则表达式,替换的字符将是一个空字符。

stringWithWhiteSpaces 在每个字符之间都包含有空格。为了去除空格,我们可以用空字符替换它们。空括号中的空字符 [] 表示字符串中的空格。

我们也可以使用 [\\s] 来获取字符串中的空白。

stringWithLowerCase 有小写和大写两种字符。我们希望用一个空字符替换每个小写字符。我们将使用 [\\p{Lower}],这是一个获取所有小写字符的正则表达式。

在 Java 中使用 String.replace() 替换字符串中的多个字符

public class ReplaceAllChars {
    public static void main(String[] args) {
        String stringWithRandomChars = "javbjavcjadakavajavc";
        String finalString = stringWithRandomChars
                .replace("b", "a")
                .replace("c", "a")
                .replace("d", "v")
                .replace("k", "j");
        System.out.println(finalString);
    }
}

输出:

javajavajavajavajava

在 JavaScript 中替换字符串的所有实例

JavaScript 允许你使用几种方法替换字符串中所有出现的字符或子字符串。

并非所有方法在速度和资源利用率方面都相同,因此在决定最佳方法之前明确定义你的用例非常重要。此外,最佳解决方案取决于你所针对的浏览器,或者更准确地说,取决于浏览器版本。

因此,较旧的浏览器可能无法理解新引入的 JavaScript 功能。例如,replaceAll 方法是最简单和最推荐的选项,但它不适用于任何 Internet Explorer 版本。值得庆幸的是,还有其他方法可以在旧版浏览器中实现相同的结果,如下所述。

使用 String.prototype.replaceAll() 内置 JavaScript 函数替换字符串的所有出现

它是迄今为止 JavaScript 中最直接的解决方案,特别是因为它是标准库的一部分。你不需要从头开始创建自己的函数,而且这种方法也比大多数其他实现要快得多。

const my_string = "abc 123 abc 456 abc 789 abc";
console.log(my_string.replaceAll("abc", "xyz"));

输出:

"xyz 123 xyz 456 xyz 789 xyz"

使用 String.prototype.replaceAll() 方法将替换字符串作为变量传递

上面的示例要求你手动输入原始字符串和替换字符串作为函数参数。如果你想将替换字符串作为变量传递,你可以使用以下方法:

const my_string = "abc 123 abc 456 abc 789 abc";
let rep_string = "xyz";
console.log(my_string.replaceAll("abc", rep_string));

输出:

"xyz 123 xyz 456 xyz 789 xyz"

事实上,你也可以将两个参数作为变量传递。如你所料,你需要做的就是创建另一个变量来存储要替换的子字符串,然后将其作为 replaceAll 方法的第一个参数传递。

const my_string = "abc 123 abc 456 abc 789 abc";
let substring = "abc";
let rep_string = "xyz";
console.log(my_string.replaceAll(substring, rep_string));

输出:

"xyz 123 xyz 456 xyz 789 xyz"

使用带有 g 标志的正则表达式来替换 JavaScript 中字符串的所有出现

获得相同结果的另一种方法是使用带有 g 标志和 replace() 方法的正则表达式。使用此方法的缺点是速度可能较慢,因此如果执行速度是你的应用程序的优先考虑因素,请尽量避免这种情况。

g 标志代表 global,如果没有它,如果你尝试执行它,代码将抛出 TypeError。在使用正则表达式对象和 replace() 方法时,这是一项要求。

const my_string = "abc 123 abc 456 abc 789 abc";
let new_string = my_string.replace(/abc/g, "xyz");
console.log(new_string)

输出:

"xyz 123 xyz 456 xyz 789 xyz"

对旧版浏览器或出于兼容性原因使用 split()join()

如上所述,旧浏览器可能无法理解新的 JavaScript 功能,就像 replaceAll() 方法一样。在这些情况下,你可以通过拆分和连接字符串来获得相同的结果。

请记住,在优化方面这是一个非常糟糕的解决方案,因此如果你的代码不适合与旧软件兼容,请避免使用此方法。

const my_string = "abc 123 abc 456 abc 789 abc";
let new_string = my_string.split("abc").join("xyz");
console.log(new_string);

输出:

"xyz 123 xyz 456 xyz 789 xyz"

很明显,一般的解决方案包括使用 split() 来搜索你要搜索的字符串,使用 join() 来替换你要替换的字符串。为了使事情更清楚,这里是你可以将原始字符串和替换字符串作为变量传递而不是硬编码它们的方法:

const my_string = "abc 123 abc 456 abc 789 abc";
original_string = "abc";
replacement_string = "xyz";
let new_string = my_string.split(original_string).join(replacement_string);
console.log(new_string);

输出:

"xyz 123 xyz 456 xyz 789 xyz"

在 JavaScript 中替换字符串中的逗号

我们将在本文中学习如何使用 replace() 方法使用 JavaScript 替换字符串中的所有逗号。

在 JavaScript 中使用 replace() 方法替换字符串中的逗号

replace() 是一个预定义的方法,我们在字符串上使用它来用另一个字符串替换该字符串的定义部分。它从完整声明的字符串中搜索定义的字符串部分,并将其替换为给定的值。

replace() 方法不会更改原始字符串,而是返回更新后的字符串。

代码:

<script>
let string = "Delft stack is a good website to learn programming"
let result = string.replace("good","best")
console.log("original string: "+string)
console.log("updated string: "+result)
</script>

输出:

"original string: Delft stack is a good website to learn programming"
"updated string: Delft stack is a best website to learn programming"

我们初始化了一个包含单词"good"的字符串,并在该字符串上使用了 replace() 方法和两个参数 replace("good","best")

它将在字符串中找到"good" 单词并将其替换为"best"

使用 JavaScript 替换字符串中的逗号

如果你只替换一个值,则只会替换第一个找到的字符串部分。我们使用带有修饰符集 (g) 的正则表达式来替换所有实例。

要替换字符串中的逗号,我们需要一个包含逗号的字符串。和上面的例子一样,我们使用 replace() 方法来替换所有逗号,例如 replace( /,/g , "other string or space" )

代码:

<script>
let string = "Delft,stack,is,a,best,website,to,learn,programming"
let resultSingle = string.replace(","," ") //replace single
let resultAll = string.replace(/,/g," ") //replace all
console.log("Original string: "+string)
console.log("Replace single: "+resultSingle)
console.log("Replace All: "+resultAll)
</script>

输出:

"Original string: Delft,stack,is,a,best,website,to,learn,programming"
"Replace single: Delft stack,is,a,best,website,to,learn,programming"
"Replace All: Delft stack is a best website to learn programming"

在上面的代码中,我们首先有一个包含逗号的初始化字符串。然后,我们应用了 replace() 方法,使用 replace(",","") 从字符串中替换单个逗号。

我们对包含正则表达式 /,/g 的字符串使用 replace() 方法来替换所有逗号。我们已经打印了原始字符串和更新字符串的日志。

在 JavaScript 中替换字符串

替换字符串的方法有多种,包括 replace() 方法、regular expressionsplit()join() 一起,以及 PHP str_replace() 方法的副本。

你可以在此处找到一篇详细的文章,该文章解释了如何使用带有和不带有 regexreplace() 方法来替换 JavaScript 中的字符串。

本教程讨论了如何在 JavaScript 中复制 PHP str_replace() 函数,以及一起使用 split()join() 方法来替换 JavaScript 中的字符串。你可以在这里找到更多关于 split()join() 的信息。

在 JavaScript 中使用 split()join() 方法替换字符串

split() 方法根据 separator 拆分原始字符串。它在不更改原始字符串的情况下输出新的子字符串数组。

join() 函数根据 separator 连接所有数组元素。它返回一个新字符串而不更新原始字符串。

JavaScript 代码:

let message = "This is a dummy text that we want to replace using replace function.";
let new_message = message.split("want").join("do not want");
console.log(new_message);

输出:

"This is a dummy text that we do not want to replace using replace function."

split() 函数在找到 want 的位置拆分 message 并返回两个子字符串 "This is a dummy text that we "" to replace using replace function."。请记住,它在破坏字符串时不会删除空格。

join() 方法将这两个子字符串与 do not want 连接起来,并输出为 "This is a dummy text, we don't want to replace using replace function."

下面的代码演示了每个函数如何操作并提供更详细的输出。

JavaScript 代码:

let message = "This is a dummy text that we want to replace using replace function.";
let split_message = message.split("want")
let new_message = split_message.join("do not want");
console.log(message);
console.log(split_message);
console.log(new_message);

输出:

"This is a dummy text that we want to replace using replace function."
["This is a dummy text that we ", " to replace using replace function."]
"This is a dummy text that we do not want to replace using replace function."

在 JavaScript 中复制 PHP str_replace() 函数来替换字符串

JavaScript 代码:

function str_replace($searchString, $replaceString, $message) {
  	// We create regext to find the occurrences
 	var regex;
 	// If the $searchString is a string
 	if ( typeof($searchString) == "string" ) {
		// Escape all the characters used by regex
 		$searchString = $searchString.replace(/[.?*+^$[\]\\(){}|-]/g, "\\");
 		regex = new RegExp("(" + $searchString + ")", "g");
    } else {
		 // Escape all the characters used by regex
 		$searchString = $searchString.map(function(i) {
 			return i.replace(/[.?*+^$[\]\\(){}|-]/g, "\\");
        });
	    regex = new RegExp("(" + $searchString.join("|") + ")", "g");
    }
 	// we create the replacement
 	var replacement;
 	// If the $searchString is a string
 	if ( typeof($replaceString) == "string" ) {
 		replacement = $replaceString;
    } else {
 		// If the $searchString is a string and the $replaceString an array
 		if ( typeof($searchString) == "string" ) {
 			replacement = $replaceString[0];
        } else {
 			// If the $searchString and $replaceString are arrays
 			replacement = function (i) {
 				return $replaceString[ $searchString.indexOf(i) ];
            }
        }
    }
	return $message.replace(regex, replacement);
}
let message = "This is a dummy text that we want to replace using replace function.";
console.log(str_replace("want", "do not want", message));

输出:

"This is a dummy text that we do not want to replace using replace function."

对于上面的示例,str_replace() 方法采用三个参数:$searchString$replaceString$message

它首先创建 regex (/[want]/g),考虑 $searchString 是否属于 string 类型而不是。然后,我们考虑各种情况创建替换

例如,如果 $searchString 是否是 string。如果不是,请检查 $searchString 是否是 string$replaceString 是否是数组或 $searchString$replaceString 是否都是数组。

最后,我们在 replace() 方法中使用此 regexreplacement 来获得所需的输出。我们可以优化上面给出的长代码以获得准确的输出。

JavaScript 代码:

function str_replace($search, $replace, $message) {
  return $message.replace(new RegExp("(" + (typeof($search) == "string" ?
      $search.replace(/[.?*+^$[\]\\(){}|-]/g, "\\") :
      $search.map(function(i) {
        return i.replace(/[.?*+^$[\]\\(){}|-]/g, "\\")
      }).join("|")) + ")", "g"), typeof($replace) == "string" ?
    $replace : typeof($search) == "string" ? $replace[0] : function(i) {
      return $replace[$search.indexOf(i)]
    });
}
let message = "This is a dummy text that we want to replace using replace function.";
console.log(str_replace("want", "do not want", message));

输出:

"This is a dummy text that we do not want to replace using replace function."