我有一个字符串变量operation_sequence
。我想从中删除另一个字符串变量job.Description
。
例如,如果我想将job.Description
添加到operation_sequence
,我可以执行以下操作:
operation_sequence += job.Description;
这是有效的。但是,如果我想从operation_sequence
中删除job.Description
,以下代码不起作用:
operation_sequence -= job.Description;
从operation_sequence
中删除job.Description
的最佳方法是什么?
您可以轻松使用String.Replace((:
String HelloWord = "Hello World!";
String NewWord= HelloWord.Replace("o","");
NewWord将是地狱
对于string
,我们不能使用-=
或-
。但是我们可以为自己的string
类实现它。
解决方案1
public class MyString
{
public string Value { get; private set; }
public MyString(string value)
{
Value = value;
}
public static MyString operator +(MyString left, MyString right)
{
return new MyString(left.Value + right.Value);
}
public static MyString operator -(MyString left, MyString right)
{
if (string.IsNullOrEmpty(left.Value))
return left;
if (string.IsNullOrEmpty(right.Value))
return left;
if (left.Value.EndsWith(right.Value))
{
int startIndex = left.Value.Length - right.Value.Length;
string result = left.Value.Substring(0, startIndex);
return new MyString(result);
}
return left;
}
public static implicit operator string(MyString value) => value.Value;
public static implicit operator MyString(string value) => new MyString(value);
}
正如您所知,我们不能使-=
和+=
过载(请参阅此(。因此,我使-
和+
过载。现在我们可以这样使用我们的类:
MyString s1 = "This is ";
MyString s2 = "just a test";
string s3 = s1 + s2; // s3 = "This is just a test"
string s4 = s3 - s2; // s4 = "This is "
因为
public static implicit operator MyString(string value) => new MyString(value)
,我们可以拥有类似MyString s1 = "test"
的东西。它隐式地将string
转换为MyString
。因为有了
public static implicit operator string(MyString value) => value.Value
,我们可以拥有类似string s3 = MyString("test")
的东西。它隐式地将MyString
转换为string
。在-运算符中,我们检查左操作数是否以右操作数结尾,然后将其删除
解决方案2
我们也可以简单地使用这样的扩展方法:public static class StringExtension
{
public static string MinusString(this string baseString, string minusString)
{
if (string.IsNullOrEmpty(baseString))
return baseString;
if (string.IsNullOrEmpty(minusString))
return baseString;
if (baseString.EndsWith(minusString))
{
int startIndex = baseString.Length - minusString.Length;
string result = baseString.Substring(0, startIndex);
return new MyString(result);
}
return baseString;
}
}
现在我们可以这样使用它:
string s = "This is just a test";
string s3 = s.MinusString("a test"); // s3 = "This is just "
s3 = s3.MinusString("just "); // s3 = "This is "
Klaus Gütter提出的解决方案对我很有效,它将operation_sequence定义为List,并在操作后使用string.Join.将其转换为字符串
private string operation_sequence;
List<string> ops = new List<string>(3);
// Add item to List:
ops.Add(job.Description);
// or Remove item from List:
ops.Remove(job.Description);
//then update operation_sequence string with values from List<string>:
operation_sequence = String.Join(", ", ops);