如何在c#中格式化此字符串

时间:2010-03-25 09:54:33

标签: c#

我有一个存储在数据库中的设置,其值为.jpg|.gif|.png。我希望在前端显示为".jpg",".gif" and ".png"在一个字符串中。例如

  

允许的格式为“.jpg”,“。gif”和“.png”

我能够使用

分隔它
string fileTypes = String.Join(",", supportedFileTypes.Split('|'))

如何在最后一个字符串之前指定和子句。它必须是动态的。例如,如果我们在数据库中有.jpg|.gif,那么它应该是

  

允许的格式为“.jpg”和“.gif”。

9 个答案:

答案 0 :(得分:7)

public String formatAllowed(String allowedFormats)
{
    String[] formats = allowedFormats.Split('|');

    if (formats.Length == 1)
        return formats[0];

    StringBuilder sb = new StringBuilder(formats[0]);

    for (int i = 1; i < formats.Length - 1; i++)
    {   
        sb.AppendFormat(",\"{0}\"", formats[i]);
    }

    sb.AppendFormat(" and \"{0}\"", formats[formats.Length - 1]);

    return sb.ToString();
}

答案 1 :(得分:3)

如果你想在一个声明中,我们可以这样做

return  allowedFormats.IndexOf("|")>=0? string.Format("Allowed formats are {0}", allowedFormats.Insert(allowedFormats.LastIndexOf("|"), "and").Replace("and|", "and").Replace("|", ",")): allowedFormats; 

答案 2 :(得分:1)

    String[] formats = ucBrandLogoFileUploadControl.Split('|');
    String output = "Allowed formats are ";
    for (int i = 0; i < formats.Length; i++)
    {
        if (i > 0)
        {
            if (i < formats.Length - 1) { output += ", "; }
            else { output += " and "; }
        }
        output += "\"" + formats[i] + "\"";
    }

答案 3 :(得分:1)

我对现有答案不满意,因为他们没有处理“允许格式”前缀,这也应该有所不同:

public static string FormatAllowed(string allowedFormats)
{
    var formats = allowedFormats.Split(new[] {'|'}, 
                            StringSplitOptions.RemoveEmptyEntries);

    return formats.Length == 0 ? "No formats allowed" :

           formats.Length == 1 ? "Allowed format is \"" + formats[0] + "\"" :

           string.Join("", 
               formats.Select(
                   (format, index) => 
                       (index == 0 ? "Allowed formats are " :
                       (index == formats.Length - 1 ? " and " : ", ")) +
                       "\"" + format + "\"")
                      .ToArray());
}

像这样测试:

static void Check(string formats, string expected)
{
    var result = FormatAllowed(formats);
    Console.WriteLine(result);
    Debug.Assert(result == expected);
}

static void Main(string[] args)
{
    Check("", "No formats allowed");
    Check(".jpg", "Allowed format is \".jpg\"");
    Check(".jpg|.png", "Allowed formats are \".jpg\" and \".png\"");
    Check(".jpg|.gif|.png", "Allowed formats are \".jpg\", \".gif\" and \".png\"");
    Check(".jpg|.gif|.png|.txt", "Allowed formats are \".jpg\", \".gif\", \".png\" and \".txt\"");
}

答案 4 :(得分:0)

让我们试试这样的

string result = "Allowed formats are ";
string[] tmp = ucBrandLogoFileUploadControl.SupportedFileTypes.Split('|');
if (tmp.Length == 1)
    result += tmp[0];
else
{
    string[] tmp2 = new string[tmp.Length-1];
    Array.Copy(tmp, tmp2, tmp.Length-1);
    result += String.Join(",",tmp2) + " and " + tmp[tmp.Length-1];
}

答案 5 :(得分:0)

public static void Main()
{
    Console.Out.WriteLine(Format("")); // no entries
    Console.Out.WriteLine(Format(".jpg"));  // one entry
    Console.Out.WriteLine(Format(".jpg|.gif")); // two entries
    Console.Out.WriteLine(Format(".jpg|.gif|.png")); // three entries
    Console.In.ReadLine();
}

private static string Format(string extensionsText)
{
    string[] extensions = extensionsText.Split('|');

    if (extensions[0] == string.Empty) return "No formats are allowed";
    if (extensions.Length == 1) return string.Format("Allowed format is \"{0}\".", extensions[0]);

    var message = new StringBuilder("Allowed formats are ");

    // first entry
    message.Append('"').Append(extensions[0]).Append('"');

    // middle entries
    for (int index = 1; index < extensions.Length - 1; index += 1)
    {
        message.Append(", ");
        message.Append('"').Append(extensions[index]).Append('"');
    }

    // last entry
    message.Append(" and ");
    message.Append('"').Append(extensions[extensions.Length - 1]).Append('"');

    message.Append('.');

    return message.ToString();
}

输出:

No formats are allowed
Allowed format is ".jpg".
Allowed formats are ".jpg" and ".gif".
Allowed formats are ".jpg", ".gif" and ".png".

答案 6 :(得分:0)

string[] fileTypes = supportedFileTypes.Split('|');
switch (fileTypes.Length)
{
    case 0 : return "No format allowed";
    case 1 : return String.Format("Allowed format is \"{0}\".", fileTypes[0]);
    case 2 : return String.Format("Allowed formats are \"{0}\" and \"{1}\".", fileTypes[0], fileTypes[1]);
    default :
        string temp = "";
        for (int i = 0; i < fileTypes.Length - 2; i++)
        {
            temp += String.Format(\"{0}\, ", fileTypes[i]);
        }
        return String.Format("Allowed formats are {0} \"{1}\" and \"{2}\".", temp, fileTypes[fileTypes.Length - 2], fileTypes[fileTypes.Length - 1]);
}

答案 7 :(得分:0)

使用linq非常简单:

public static string SupportedFilesToDisplayString(string supportedFileTypes)
{
    if (supportedFileTypes == null)
    {
        throw new ArgumentNullException("supportedFileTypes");
    }

    var fileTypes = supportedFileTypes.Split('|')
        .Select(s => string.Format("\"{0}\"", s));
    var lastFileType = fileTypes.Skip(fileTypes.Count() - 1).SingleOrDefault();
    var otherFileTypes = fileTypes.Take(fileTypes.Count() - 1);
    if (otherFileTypes.Any())
    {
        var otherString = String.Join(", ", otherFileTypes.ToArray());
        return string.Format("{0} and {1}", otherString, lastFileType);
    }
    else
    {
        return lastFileType;
    }
}

Snippet编译器中的小测试:

public static void RunSnippet()
{
    WL(SupportedFilesToDisplayString(".jpg|.gif|.png"));
    WL(SupportedFilesToDisplayString(".jpg|.png"));
    WL(SupportedFilesToDisplayString(".png"));
    WL(SupportedFilesToDisplayString(""));
    WL(SupportedFilesToDisplayString(null));
}

显示:

".jpg", ".gif" and ".png"
".jpg", ".gif" and ".png"
".jpg" and ".png"
".png"
""
---
The following error occurred while executing the snippet:
System.ArgumentNullException: Value cannot be null.
Parameter name: supportedFileTypes
   at MyClass.SupportedFilesToDisplayString(String supportedFileTypes)
   at MyClass.RunSnippet()
   at MyClass.Main()
---

答案 8 :(得分:0)

string.Format("Allowed formats are \"{0}\"",
              supportedFileTypes.Insert(supportedFileTypes.LastIndexOf("|"), "|")
                .Replace("||", "\" and \"")
                .Replace("|", "\",\""))