簡體   English   中英

如何在C#中的for循環中修剪和附加字符串

[英]how to trim and append a string in for loop in c#

如何在c#中的for循環中修剪和附加一個字符串,我有一個類似於"\\Examp"l'e"的字符串,我想要的是使用每個循環從中獲取示例:

string value = @"\Examp"l'e";

foreach(string trim in value)
{
    if(trim == @"\")
    {
        \\how to trim the value like Examp"l'e
    }
    if(trim == @""")
    {
        \\again trim
    }
    if(trim == @"'")
    {
        \\again trim
    }
}

我的最終輸出應該是: Example

考慮使用string.Replace來完成任務,這會更容易:

string value = @"\Examp""l'e";
string final = value
   .Replace("\"", string.Empty)
   .Replace("\\", string.Empty)
   .Replace("'", string.Empty);

蠻力解決方案

trim.replace(oldvalue,"");

更好的方法

Regex.Replace(trim, @"\\"'", "");

我沒有嘗試過此代碼,我打算用正則表達式進行修剪。

string value = @"\Examp"l'e";
value = value.Replace(@"\","").Replace("\"","").Replace("\'","");

我會使用正則表達式:

Regex reg = new Regex(@"[\"']");
string value = @"\Examp"l'e";
string output = reg.Replace(value,String.Empty);

這將用一個空字符串替換正則表達式中括號之間的每個字符。

您可以使用循環和String.Replace (因為您實際上不想從開頭和開頭,也從中間刪除這些字符):

string value = "\\Examp\"l'e";

string[] replaceAll = {"\\","\"", "'"};
foreach(string str in replaceAll)
    value = value.Replace(str, ""); 

Console.Write(value); // Example

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM