这里是我要实现的示例:例如,给定字符串Something
,如果要将所有出现的so
替换为DDD
,结果将是DDDmething
。
这是我实施的方式;我的代码通过其特定位置找到了一个字符并对其进行了更改,但实际上我想实现上面所述的内容。
static void Main(string[] args)
{
string str = "The Haunting of Hill House!";
Console.WriteLine("String: " + str);
// replacing character at position 7
int pos = 7;
char rep = 'p';
string res = str.Substring(0, pos) + rep + str.Substring(pos + 1);
Console.WriteLine("String after replacing a character: " + result);
Console.ReadLine();
}
答案 0 :(得分:1)
这应该做您想要的。这个想法是使用IndexOf
查找要替换的子字符串的索引,然后在替换之前附加子字符串,然后从找到的子字符串的末尾开始搜索。然后,在找到并替换所有子字符串之后,如果有的话,将原始字符串的其余部分追加到末尾。
请注意,这不会对输入进行任何检查,您确实应该使用string.Replace
,因为我确信它的性能更高。
public string Replace(string input, string find, string replace)
{
// The current index in the string where we are searching from
int currIndex = 0;
// The index of the next substring to replace
int index = input.IndexOf(find);
// A string builder used to build the new string
var builder = new StringBuilder();
// Continue until the substring is not found
while(index != -1)
{
// If the current index is not equal to the substring location
// when we need to append everything from the current position
// to where we found the substring
if(index != currIndex )
{
builder.Append(input.Substring(currIndex , index - currIndex));
}
// Now append the replacement
builder.Append(replace);
// Move the current position past the found substring
currIndex = index + find.Length;
// Search for the next substring.
index = input.IndexOf(find, currIndex );
}
// If the current position is not the end of the string we need
// to append the remainder of the string.
if(currIndex < input.Length)
{
builder.Append(input.Substring(currIndex));
}
return builder.ToString();
}
答案 1 :(得分:1)
替代方法可能是用“ so”分割字符串,并用“ DDD”合并结果数组:
string result = string.Join("DDD", "something".Split(new[] { "so" }, StringSplitOptions.None));
答案 2 :(得分:0)
您可以这样做:
var someString = "This is some sort of string.";
var resultIndex = 0;
var searchKey ="So";
var replacementString = "DDD";
while ((resultIndex = someString.IndexOf(searchKey, resultIndex, StringComparison.OrdinalIgnoreCase)) != -1)
{
var prefix = someString.Substring(0, Math.Max(0, resultIndex - 1));
var suffix = someString.Substring(resultIndex + searchKey.Length);
someString = prefix + replacementString + suffix;
resultIndex += searchKey.Length;
}
预期产生“这是字符串的DDDme DDDrt。” 。