本文展示了几种通过修改现有string来生成string的技术。 所有演示的技术都以新 string 对象的形式返回修改的结果。 为了演示原始字符串和修改后的字符串是不同的实例,示例将结果存储在新变量中。 可以在运行每个示例时检查原始 string 和新的修改 string 。
本文演示了几种技术。 可以替换现有文本。 可以搜索模式,并将匹配的文本替换为其他文本。 可以将字符串视为字符序列。 还可以使用删除空白的便利方法。 选择最符合方案的技术。
替换文本
以下代码通过将现有文本替换为替换项来创建新的字符串。
string source = "The mountains are behind the clouds today.";
// Replace one substring with another with String.Replace.
// Only exact matches are supported.
var replacement = source.Replace("mountains", "peaks");
Console.WriteLine($"The source string is <{source}>");
Console.WriteLine($"The updated string is <{replacement}>");
前面的代码演示了字符串的 不可变 属性。 在前面的示例中可以看到,原始字符串 source未修改。 该 String.Replace 方法将创建一个包含修改的新 string。
该方法 Replace 可以替换字符串或单个字符。 在这两种情况下,都会替换所寻求文本的每个匹配项。 以下示例将所有 '' 字符替换为 '_':
string source = "The mountains are behind the clouds today.";
// Replace all occurrences of one char with another.
var replacement = source.Replace(' ', '_');
Console.WriteLine(source);
Console.WriteLine(replacement);
源字符串保持不变,并在替换操作后返回新字符串。
去除空白
可以使用String.Trim和String.TrimStartString.TrimEnd方法删除任何前导空格或尾随空格。 下面的代码就是删除两种空格的示例。 源字符串不会更改;这些方法返回具有修改内容的新字符串。
// Remove trailing and leading white space.
string source = " I'm wider than I need to be. ";
// Store the results in a new string variable.
var trimmedResult = source.Trim();
var trimLeading = source.TrimStart();
var trimTrailing = source.TrimEnd();
Console.WriteLine($"<{source}>");
Console.WriteLine($"<{trimmedResult}>");
Console.WriteLine($"<{trimLeading}>");
Console.WriteLine($"<{trimTrailing}>");
删除文本
可以使用该方法从字符串 String.Remove 中删除文本。 此方法删除从特定索引开始的指定字符数。 以下示例演示如何使用 String.IndexOf 配合 Remove 从字符串中删除文本:
string source = "Many mountains are behind many clouds today.";
// Remove a substring from the middle of the string.
string toRemove = "many ";
string result = string.Empty;
int i = source.IndexOf(toRemove);
if (i >= 0)
{
result= source.Remove(i, toRemove.Length);
}
Console.WriteLine(source);
Console.WriteLine(result);
替换匹配模式
可以使用 正则表达式 将文本匹配模式替换为可能由模式定义的新文本。 以下示例使用 System.Text.RegularExpressions.Regex 类在源字符串中查找模式,并将其替换为正确的大写。 该方法 Regex.Replace(String, String, MatchEvaluator, RegexOptions) 采用一个函数,该函数提供替换的逻辑作为其参数之一。 在此示例中, LocalReplaceMatchCase 该函数是在示例方法中声明的 本地函数 。
LocalReplaceMatchCase 使用 System.Text.StringBuilder 类生成具有适当大写的替换字符串。
正则表达式最适用于搜索和替换遵循模式的文本,而不是已知文本。 有关详细信息,请参阅 如何搜索字符串。 搜索模式“the\s”用于查找单词“the”,其后跟随一个空格字符。 该模式的这一部分可确保它与源字符串中的“there”不匹配。 有关正则表达式语言元素的详细信息,请参阅 正则表达式语言 - 快速参考。
string source = "The mountains are still there behind the clouds today.";
// Use Regex.Replace for more flexibility.
// Replace "the" or "The" with "many" or "Many".
// using System.Text.RegularExpressions
string replaceWith = "many ";
source = System.Text.RegularExpressions.Regex.Replace(source, """the\s""", LocalReplaceMatchCase,
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
Console.WriteLine(source);
string LocalReplaceMatchCase(System.Text.RegularExpressions.Match matchExpression)
{
// Test whether the match is capitalized
if (Char.IsUpper(matchExpression.Value[0]))
{
// Capitalize the replacement string
System.Text.StringBuilder replacementBuilder = new System.Text.StringBuilder(replaceWith);
replacementBuilder[0] = Char.ToUpper(replacementBuilder[0]);
return replacementBuilder.ToString();
}
else
{
return replaceWith;
}
}
该方法 StringBuilder.ToString 返回一个不可变字符串,其中包含对象中 StringBuilder 的内容。
修改单个字符
可以从字符串生成字符数组,修改数组的内容,然后根据数组的修改内容创建新字符串。
以下示例演示如何替换字符串中的一组字符。 首先,它使用 String.ToCharArray() 该方法创建字符数组。 它使用IndexOf方法查找单词“fox”的起始索引。将以下三个字符替换为其他的单词。 最后,从更新的字符数组构造一个新字符串。
string phrase = "The quick brown fox jumps over the fence";
Console.WriteLine(phrase);
char[] phraseAsChars = phrase.ToCharArray();
int animalIndex = phrase.IndexOf("fox");
if (animalIndex != -1)
{
phraseAsChars[animalIndex++] = 'c';
phraseAsChars[animalIndex++] = 'a';
phraseAsChars[animalIndex] = 't';
}
string updatedPhrase = new string(phraseAsChars);
Console.WriteLine(updatedPhrase);
以编程方式构建字符串内容
由于字符串是不可变的,前面的示例都创建临时字符串或字符数组。 在高性能场景中,应尽量避免这些堆分配。 .NET 提供了一种方法 String.Create ,允许你通过回调以编程方式填充字符串的字符内容,同时避免中间临时字符串分配。
// constructing a string from a char array, prefix it with some additional characters
char[] chars = [ 'a', 'b', 'c', 'd', '\0' ];
int length = chars.Length + 2;
string result = string.Create(length, chars, (Span<char> strContent, char[] charArray) =>
{
strContent[0] = '0';
strContent[1] = '1';
for (int i = 0; i < charArray.Length; i++)
{
strContent[i + 2] = charArray[i];
}
});
Console.WriteLine(result);
可以使用不安全代码修改固定块中的字符串,但 强烈建议 不要在创建字符串后修改字符串内容。 这样做会导致不可预知的错误。 例如,如果某人实习生的字符串中的内容与你的字符串相同,他们会收到你的副本,但没想到你正在修改其字符串。