如何在字符串中添加新字符 [英] How to add new characters to a string
问题描述
我需要在字符串中的不同单词上添加单引号.例如.将此字符串从:我,我自己,我更改为:我",我自己",我".请注意,我需要在每个单词上添加单引号,同时保持逗号
I need to add single quotation marks to different words in a string. E.g. Change this string from: me, myself, i to: ''me'', ''myself'', ''i''. Notice that i need to add single quotation marks to each word while maintaining the commas
推荐答案
惊奇:您不能在字符串中添加任何内容.字符串是不可变的.
您只能使用一个或多个其他字符串作为字符串数据源来创建一个全新的字符串.为此,可以使用string.Format
.例如:
Surprise: you cannot add anything to a strings. Strings are immutable.
You can only create a brand-new string using one or more of other strings as a source of string data. For this purpose, you can usestring.Format
. For example:
string pronoun = //...
string quotedPronoun = string.Format("'{0}'", pronoun);
要将原始字符串分解为字符串数组,请使用string.Split
:
To decompose your original string into array of strings use string.Split
:
string pronouns[] = sourceString.Split(
new string[] {',', ' '},
StringSplitOptions.RemoveEmptyEntries);
string[] newPronouns = new string[pronouns.Length];
int counter = 0;
foreach (string pronoun in pronouns) {
newPronouns[index] = string.Format("'{0}'", pronoun);
++counter;
}
要组成数组,请使用string.Join
:
To compose in the array, use string.Join
:
string result = string.Join(", ", newPronouns);
不要使用重复的字符串连接,因为这是非常无效的:字符串是不可变的.使用System.Text.StringBuilder
.
Do not use repeated string concatenation, because this is very ineffective: strings are immutable. Use System.Text.StringBuilder
.
从技术上讲,字符串不能一成不变,一旦创建就不能更改.
但是,实际上,您可以使它看起来像您一样!正则表达式使其非常简单:
Technically, you can''t strings are immutable and cannot be changed once they are created.
However, in practice you can make it look like you have! A regex makes it pretty simple:
public static Regex regex = new Regex(
"\\w+",
RegexOptions.IgnoreCase
| RegexOptions.CultureInvariant
| RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled
);
// This is the replacement string
public static string regexReplace =
"''
&''"; //// Replace the matched text in the InputText using the replacement pattern string result = regex.Replace(InputText,regexReplace);
&''"; //// Replace the matched text in the InputText using the replacement pattern string result = regex.Replace(InputText,regexReplace);
这篇关于如何在字符串中添加新字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!