我有一些字符串,例如
string word = "This is example text/WS95 1300 G934 100 DAB"
我想删除WS95和G934之间的字符串,因此结果将是: “这是示例文本/ WS95 G934 100 DAB”
有什么办法吗?我尝试使用indexof
int start = word.IndexOf("WS95") + "WS95".length;
int end = word.LastIndexOf("G");
在那之后,我被困住了。
也许有人对此有任何想法吗?
预期结果:“这是示例文本/ WS95 G934 100 DAB”
谢谢
答案 0 :(得分:3)
尝试一下。
string word = "This is example text/WS95 1300 G934 100 DAB";
var result = Regex.Replace(word, @"(?<=WS95).*(?= G934)","");
或
string word = "This is example text/WS95 1300 G934 100 DAB";
var match = Regex.Matches(word, @"(.*WS95)(.*1300)(.*)")[0];
var result = match.Groups[1].Value+match.Groups[3].Value;
答案 1 :(得分:1)
var key1 = "WS95";
var key2 = "G934";
string word = "This is example text/WS95 1300 G934 100 DAB";
var resultStrings = word.Split(new[] { key1 }, StringSplitOptions.None);
var resultStrings2 = resultStrings[1].Split(new[] { key2 }, StringSplitOptions.None);
var result = resultStrings[0] + key1 +" "+ key2 + resultStrings2[1];
答案 2 :(得分:1)
根据给定的字符串。
string name = "This is example text/WS95 1300 G934 100 DAB";
Console.WriteLine("The entire string is '{0}'", name);
// remove the contents, identified by finding the `WS95` and `G934` in the string...
int foundS1 = name.IndexOf("WS95");
int foundS2 = name.IndexOf("G934", foundS1 + 1);
if (foundS1 != foundS2 && foundS1 >= 0) {
name = name.Remove(foundS1 + 4, (foundS2-5) - foundS1);
Console.WriteLine("After removing '{0}'", name);
}
小提琴链接:C# Fiddle Link.
答案 3 :(得分:0)
尝试
string word = "This is example text/WS95 1300 G934 100 DAB";
int start = word.IndexOf("WS95") + "WS95".Length;
int end = word.IndexOf("1300")+"1300".Length;
string tmp1 = word.Substring(0, start);
string tmp2=word.Substring(end);
string result = tmp1 + tmp2;
答案 4 :(得分:0)
如果您的单词始终以空格分隔,并且您希望/不介意删除多余的空格,请采用以下一种方法:
string word = "This is example text/WS95 1300 G934 100 DAB";
string[] array = word.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
int index1 = Array.IndexOf(array, "text/WS95"); // has to be a whole word between spaces
int index2 = Array.IndexOf(array,"G934");
var result = String.Join(" ",array.Take(index1 + 1).Concat(array.Skip(index2)));