簡體   English   中英

使用C#進行字符串格式化

[英]String formatting using C#

有沒有一種方法可以從字符串中刪除每個特殊字符,例如:

"\r\n               1802 S St Nw<br>\r\n                    Washington, DC 20009"

就像這樣寫:

"1802 S St Nw, Washington, DC 20009"

刪除特殊字符:

public static string ClearSpecialChars(this string input)
{
    foreach (var ch in new[] { "\r", "\n", "<br>", etc })
    {
        input = input.Replace(ch, String.Empty);
    }
    return input;
}

要將所有雙倍空格替換為單個空格:

public static string ClearDoubleSpaces(this string input)
{
    while (input.Contains("  ")) // double
    {
        input = input.Replace("  ", " "); // with single
    }
    return input;
}

您也可以將兩種方法拆分為一個方法:

public static string Clear(this string input)
{
    return input
        .ClearSpecialChars()
        .ClearDoubleSpaces()
        .Trim();
}

有兩種方法,可以使用RegEx,也可以使用String.Replace(...)

使用Regex.Replace()方法,將要刪除的所有字符指定為要匹配的模式。

您可以使用C#Trim()方法,如下所示:

http://msdn.microsoft.com/de-de/library/d4tt83f9%28VS.80%29.aspx

System.Text.RegularExpressions.Regex.Replace("\"\\r\\n                                                            1802 S St Nw<br>\\r\\n                                                            Washington, DC 20009\"", 
 @"(<br>)*?\\r\\n\s+", "");

也許是這樣,使用ASCII整型值。 假設所有html標簽都將關閉。

public static class StringExtensions
{
    public static string Clean(this string str)
    {   
        string[] split = str.Split(' ');

        List<string> strings = new List<string>();
        foreach (string splitStr in split)
        { 
            if (splitStr.Length > 0)
            {
                StringBuilder sb = new StringBuilder();
                bool tagOpened = false;

                foreach (char c in splitStr)
                {
                    int iC = (int)c;
                    if (iC > 32)
                    {
                        if (iC == 60)
                            tagOpened = true;

                        if (!tagOpened)
                               sb.Append(c);

                        if (iC == 62)
                            tagOpened = false;
                    }
                }

                string result = sb.ToString();   

                if (result.Length > 0)
                    strings.Add(result);
            }
        }

        return string.Join(" ", strings.ToArray());
    }
}

暫無
暫無

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

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