[英]Find and replace a part of a string c#
I have an SQL query in a string and I want to replace a part of the string with a new value.我在字符串中有一个 SQL 查询,我想用新值替换字符串的一部分。
The part in the string I'm looking for is a: until it hits either a, or a ).我要查找的字符串中的部分是 a: 直到它命中 a 或 a )。 The part it finds needs to be replaced by a question mark.
它找到的部分需要用问号替换。
I've been working on this for a while but I can't seem to find a solution how to fix this.我已经为此工作了一段时间,但我似乎无法找到解决此问题的解决方案。
Can anyone help me further?任何人都可以进一步帮助我吗?
Example String I want to get a part of:我想获得的示例字符串:
"INSERT INTO ORDERS ( ORDER_ID, CUSTNO, COMPANY_NAME, ITEM, AMOUNT1, AMOUNT2) 
VALUES ( :WS_ORDER_ID, :WS_ORDER_CUSTNO, :WS_ORDER_COMPANY_NAME, :WS_ITEM, :WS_AMOUNT1, :WS_AMOUNT2)"
So what I want the string to look like is:所以我希望字符串看起来像:
"INSERT INTO ORDERS ( ORDER_ID, CUSTNO, COMPANY_NAME, ITEM, AMOUNT1, AMOUNT2) 
VALUES ( ?, ?, ?, ?, ?, ?)"
What i was trying to create:我试图创造的东西:
public String Replace(String value, String firstValue, String lastValue, String replacementValue) {
int firstLocation = value.IndexOf(firstValue);
var lastLocation = value.IndexOf(lastValue);
if (value.Contains(firstValue)) {
String modifiedValue;
modifiedValue = value.IndexOf(Convert.ToChar(firstLocation), lastLocation.ToString());
String newValue = value.Replace(modifiedValue, replacementValue);
}
return newValue;
}
Something like this but I can't figure it out.像这样的东西,但我无法弄清楚。
And then I want to have a foreach loop that takes this method and replaces every:WORD, with a?.然后我想要一个 foreach 循环,它采用这种方法并用 a? 替换每个:WORD。
Best regards此致
A simple method like this should do the trick if ':' is guaranteed to be unique as a token:如果 ':' 保证作为令牌是唯一的,那么像这样的简单方法应该可以解决问题:
public string Replace(string text)
{
string[] items = text.Split(':');
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append(items[0]);
for(int i=1;i<items.Length;i++)
{
string item = items[i].TrimEnd();
stringBuilder.Append("?" + item[item.Length - 1]);
}
return stringBuilder.ToString();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.