我想创建一个可以替换字符串中特定单词的程序。
示例单词:
Dim sample As String = "TWINKLE TWINKLE LITTLE STAR FISH"
我想将第二个单词TWINKLE替换为MAD,因此新输出将是:
TWINKLE MAD LITTLE STAR FISH"
这可能吗?
请注意
sample.text = sample.Replace("TWINKLE", "MAD")
功能将取代TWINKLE到MAD和O / P将
"MAD MAD LITTLE STAR FISH"
我不想要的。只应更改第二个Twinkle
答案 0 :(得分:0)
此方法应该有效,它只使用IndexOf
或Substring
等字符串方法:
Public Shared Function ReplaceNthValue(input As String, oldValue As String, newValue As String, nth As Int32, Optional comparison As StringComparison = StringComparison.CurrentCulture) As String
Dim index As Int32 = input.IndexOf(oldValue, comparison)
If index = -1 Then
Return input
End If
Dim counter As Int32 = 0
While index >= 0
counter += 1
If counter = nth Then
Dim before As String = input.Substring(0, index)
Dim after = input.Substring(index + oldValue.Length)
Return String.Format("{0}{1}{2}", before, newValue, after)
End If
index = input.IndexOf(oldValue, index + oldValue.Length, comparison)
End While
Return input
End Function
您的样本:
Dim sample As String = "TWINKLE TWINKLE LITTLE STAR FISH"
Console.Write(ReplaceNthValue(sample, "TWINKLE", "MAD", 2))
输出:
TWINKLE MAD LITTLE STAR FISH
答案 1 :(得分:0)
这有效:
Public Shared Function ReplaceNthValue(input As String, oldValue As String, newValue As String, nth As Int32, Optional comparison As StringComparison = StringComparison.CurrentCulture) As String
Dim parts = input.Split(New String() { oldValue }, StringSplitOptions.None)
Dim replacements = parts.Skip(1).Select(Function (x, i) if(i = nth - 1, newValue, oldValue))
Return String.Join("", parts.Take(1).Concat(replacements.Zip(parts.Skip(1), Function (r, p) New String() { r, p }).SelectMany(Function (x) x)))
End Function
为此:
Dim sample As String = "TWINKLE TWINKLE LITTLE STAR FISH"
Console.Write(ReplaceNthValue(sample, "TWINKLE", "MAD", 2))
我明白了:
TWINKLE MAD LITTLE STAR FISH