如何替换字符串中的文本 [英] How to replace text in a string
问题描述
这是我的代码,我想以最简单的方式将"here"一词替换为"potato".
This is my code, I want to replace the word "here" with "potato" in the simplest way.
Private Sub btnreplace_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnreplace.Click
txttyping.Text.Replace("here", "potato")
End Sub
推荐答案
字符串(文本)是不可变的.这意味着它们不能直接更改,只能更改一个新字符串已创建/返回.
Strings (text) are immutable. This means they cannot be changed directly, to alter one, a new string is created/returned.
txttyping.Text = txttyping.Text.Replace("here", "potato)
Replace()
返回需要分配的新字符串.更改字符串的 all String
方法都是这样: ToLower()
, ToUpper()
, Remove()
,PadLeft(), Copy()
, Remove()
, TrimEnd()
.
Replace()
returns a new string which needs to be assigned. This is true for all the String
methods which change the string: ToLower()
, ToUpper()
, Remove()
, PadLeft(), Copy()
, Remove()
, TrimEnd()
.
请参见 MSDN字符串类:
一个String对象被称为不可变的(只读),因为它的值在创建后就无法修改.看来可以修改String对象的方法实际上会返回一个包含修改的新String对象.
A String object is called immutable (read-only), because its value cannot be modified after it has been created. Methods that appear to modify a String object actually return a new String object that contains the modification.
这篇关于如何替换字符串中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!