C# 替换字符串中出现的特定单词
考虑以下示例:我有一个字符串“Word1Word1Word1Word1”。我想被替换为第一个单词和最后一个单词C# 替换字符串中出现的特定单词,c#,string,replace,word,C#,String,Replace,Word,考虑以下示例:我有一个字符串“Word1Word1Word1Word1”。我想被替换为第一个单词和最后一个单词 我如何做到这一点?关于你的另一个问题,我假设你使用.NET,如果是这样的话: 编辑:此示例将替换第一个和最后一个单词: static void Main(string[] args) { string test = "word1 word1 word1 word1"; Console.WriteLine(test); // R
我如何做到这一点?关于你的另一个问题,我假设你使用.NET,如果是这样的话: 编辑:此示例将替换第一个和最后一个单词:
static void Main(string[] args)
{
string test = "word1 word1 word1 word1";
Console.WriteLine(test);
// Replace words
test = ReplaceWords(test, "word1", "test");
Console.WriteLine(test);
Console.ReadLine();
}
static string ReplaceWords(string input, string word, string replaceWith)
{
// Replace first word
int firstIndex = input.IndexOf(word);
input = input.Remove(firstIndex, word.Length);
input = input.Insert(firstIndex, replaceWith);
// Replace last word
int lastIndex = input.LastIndexOf(word);
input = input.Remove(lastIndex, word.Length);
input = input.Insert(lastIndex, replaceWith);
return input;
}
你用哪种语言?请提供更多信息。您正在使用/打算使用哪种语言,到目前为止您尝试了什么?在我看来,你做的研究很少。是的,我正在使用.Net。但是我怎样才能用另一个词替换这些提取的词呢?我已经用一个代码更新了答案,这个代码实际上替换了第一个和最后一个词。