Skatz1990 Skatz1990 - 28 days ago 5
C# Question

C# string format unkown size

Let's say I have the following string:

string postData = "state={2}&country={3}&geolocation={0}&city={1}";


And I have another list of strings. Its size could be in this case 4 at most.
I'm trying to create a method which replaces the numbers in my postData variable, depending on the list size. Something like the following method:

private string UnknownSizeStringFormat(string postData, params string[] stringsToReplace)
{
return string.format(postData, stringsToReplace);
}


The above method works as long as the list's size is 4. The thing is, on the first call, my list's size could be smaller than 4, so if it's 0 for example, I would like to replace each number inside the brackets with an empty string. My return value should be:

"state=&country=&geolocation=&city="


If its size is one, and the first member in the list is "21,27" my return string should be:

"state=&country=&geolocation=21,27&city="


And so on...
I could use a loop or a Regular Expression for this purpose but I've been wondering if there is a better way, a Linq solution perhaps? What I do know is how many numbers postData could have at most, which in my case is 4.
Again, I could do that with a loop or a Regular Expression, but I'm trying to make it as short as possible

Edit: The postData string could vary. That was just an example. Its size or content could be different

Answer

What I do know is how many numbers postData could have at most

Then how about this:

static string UnknownSizeStringFormat(string format, int maxArgs, params object[] args)
{
    Array.Resize(ref args, maxArgs);
    return string.Format(format, args);
}

so you can use:

string postData = "state={2}&country={3}&geolocation={0}&city={1}";
var result = UnknownSizeStringFormat(postData, 4);