[英]Removing the last two or multiple words from a string in c#
我可能有繩子
select 'abc','xyz','123' Union all select 'def','wer','456' Union all
該字符串是由循環生成的,例如
foreach(var item in obj)
{
" SELECT'" + item.a + "'," + item.b + ," + item.c + "UNION ALL";
}
現在我想刪除"Union all"
寫在最后的string.How的我能做到這一點是單一的或者使用C#.IndexOf正則表達式不會工作,因為我有多個"Union all"
在我的字符串。
據我所知,您正在嘗試從多個select
構建finalQuery
。 您可以在Join
的幫助下做到這一點:
string[] selects = new string[] {
"select 'abc','xyz','123'",
"select 'def','pqr','456'",
};
// select 'abc','xyz','123' Union all select 'def','pqr','456'
string finalQuery = string.Join(" Union all ", selects);
但是,如果要刪除最后一個Union all
,則可以使用EndsWith
測試字符串:
string finalQuery = myString.EndsWith("Union all")
? myString.Substring(0, myString.Length - "Union all".Length)
: myString;
編輯:如果在循環中生成selects
(請參見下面的注釋),則可以嘗試提取將loop
轉換為IEnumerable<String>
:
private IEnumerable<string> MySelects() {
foreach(var item in obj) {
// Some Logic Here...
// When you are ready to create a select just "yield return" it and keep looping
yield return $" SELECT '{item.a}', '{item.b}', '{item.c}'";
// Some Other Logic Here...
}
}
然后再次Join
:
string finalQuery = string.Join(" Union all ", MySelects());
最后,如果您想循環播放(無論出於何種原因),請添加if
:
StringBuilder sb = new StringBuilder();
foreach(var item in obj) {
// if we have a query, next one should be add via "UNION ALL"
if (sb.Length > 0)
sb.Append(" UNION ALL ");
sb.Append($"SELECT '{item.a}', '{item.b}', '{item.c}'");
}
string finalQuery = sb.ToString();
您可以結合使用string.Join
和LINQ Skip
:
string input = "select 'abc','xyz','123' Union all select 'def','wer','456' Union all";
string result = string.Join(" ", input.Split(' ').Reverse().Skip(2).Reverse());
我將從這樣的somelink開始。 如果替換變得更加復雜,則可以開始使用正則表達式。
var toRemove = "Union all";
if (yourString.EndWith(toRemove ))
{
yourString = yourString.SubString(0, yourString.Length - toRemove.Length).Trim();
}
PS從某個邏輯位置獲取toRemove字符串,請勿在您的過程中使用該字符串,以避免使用魔術值。
您可以將此用作函數;
var toRemove = "Union all";
if (string.IsNullOrWhiteSpace(yourString))
return;
var pos = yourString.LastIndexOf(stringToFind);
if (pos < 0) return;
string newString = yourString.Remove(pos, yourString.Length);
return newString;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.