开发者

How to format this string in c#

I have a setting stored in database which has a value .jpg|.gif|.png . I want to display it on frontend as ".jpg",".gif" and 开发者_JS百科".png" in a single string. for example

Allowed formats are ".jpg",".gif" and ".png"

I was able to seperate it using

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

How to specify and clause before the last string. It has to be dynamic. For example if we have .jpg|.gif in database, it should be

Allowed formats are ".jpg" and ".gif".


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();
}


If you want in a single statement, we can do like this

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


    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] + "\"";
    }


I wouldn't be happy with the existing answers because they don't handle the "Allowed formats" prefix, which ought to vary also:

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());
}

Test it like this:

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\"");
}


let's try sth like this

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];
}


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();
}

Outputs:

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


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]);
}


Pretty simple using 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;
    }
}

Small test in Snippet compiler :

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

Display :

".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()
---


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜