Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

alternatives to string.Format(".... {0}....{1}....",v1,v2) in .net?

Tags:

string

c#

string.Format() with it's "bla {0} bla" syntax is great. But sometimes I don't want to enumerate the placeholders. Instead I just want to map the variables sequentially in the placeholders. Is there a library that can do that?

For instance, instead of

string.Format("string1={0}, string2={1}", v1, v2)

something like

string.Format("string1={*}, string2={*}", v1, v2)
like image 984
Nestor Avatar asked Nov 05 '09 23:11

Nestor


3 Answers

There is now something called string interpolation in C# 6.0 so that

        var name = "ozzy";
        var x = string.Format("Hello {0}", name);
        var y = $"Hello {name}";

equate to the same thing.

See https://msdn.microsoft.com/en-gb/magazine/dn879355.aspx

Just to add, you would frequently want to do a multi line string so that would just be:

var sql = $@"
 SELECT 
 name, age, gender
 FROM Users
 WHERE UserId = '{userId}'
 ORDER BY age asc";
like image 172
Andrew Avatar answered Sep 18 '22 03:09

Andrew


Here's a possibly faster version using Regex.Replace. Warning: no support for escaping the {*}, or nice error messages when you go out of range or don't supply enough arguments!

public static class ExtensionMethods
{
    private static Regex regexFormatSeq = new Regex(@"{\*}", RegexOptions.Compiled);

    public static string FormatSeq(this string format, params object[] args)
    {
        int i = 0;
        return regexFormatSeq.Replace(format, match => args[i++].ToString());
    }
}
like image 21
Roman Starkov Avatar answered Sep 18 '22 03:09

Roman Starkov


You could accomplish this yourself by writing your own string extension coupled with the params keyword, assuming you're using .NET 3.5 or higher.

Edit: Got bored, the code is sloppy and error prone, but put this class in your project and using its namespace if necessary:

public static class StringExtensions
{
    public static string FormatEx(this string s, params string[] parameters)
    {
        Regex r = new Regex(Regex.Escape("{*}"));

        for (int i = 0; i < parameters.Length; i++)
        {
            s = r.Replace(s, parameters[i], 1);
        }

        return s;
    }
}

Usage:

Console.WriteLine("great new {*} function {*}".FormatEx("one", "two"));
like image 40
Langdon Avatar answered Sep 19 '22 03:09

Langdon