Click here to Skip to main content
15,877,482 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I want to create a procedure I could call like this:

extraString myObject = new extraString();<br />
string myString = "The file %1 cannot be deleted with the current user %2. The file %1 is blocked by another user, please try again later";<br />
myObject.StrBuild(myString, "test.txt", "John Citizen");


For this procedure I want to pass as many parameters as I want, to replace in my original string the % + [increment number].

Something like this:

    class extraString<br />
    {<br />
        public string StrBuild(string stringToBuild, string param1)<br />
        {<br />
            StringBuilder objBuilder = new StringBuilder(stringToBuild);<br />
            objBuilder.Replace("%1", param1);<br />
            return objBuilder.ToString();<br />
        }<br />
        public string Strbuild(string stringToBuild, string param1, string param2)<br />
        {<br />
            StringBuilder objBuilder = new StringBuilder(stringToBuild);<br />
            objBuilder.Replace("%1", param1);<br />
            objBuilder.Replace("%2", param2);<br />
            return objBuilder.ToString();<br />
        }<br />
... <br />
        public string Strbuild(string stringToBuild, string param1, string param2, ..., string param20)<br />
        {<br />
            StringBuilder objBuilder = new StringBuilder(stringToBuild);<br />
            objBuilder.Replace("%1", param1);<br />
            objBuilder.Replace("%2", param2);<br />
            ...<br />
objBuilder.Replace("%20", param20);<br />
            // return the constructed string<br />
            return objBuilder.ToString();<br />
        }<br />
    }


How can I realize it without writing the 20 same methods with each time one or more parameter.

Thank you in advance.
Posted

1 solution

You can use as many parameters as you want to.
class Program
{
    static void Main(string[] args)
    {
        ExtraString myObject = new ExtraString();
        string myString = @"The file %1 cannot be deleted with the current user %2. The file %1 is blocked by another user, please try again later";
        Console.WriteLine(myObject.StrBuild(myString, new string[]{"test.txt", "John Citizen"}));
    }
}

class ExtraString
{
    public string StrBuild(string stringToBuild, string[] parameters)
    {
        StringBuilder objBuilder = new StringBuilder(stringToBuild);
        for (int i=0;i<parameters.Length;i++)
        {
            objBuilder.Replace(@"%"+(i+1).ToString(), parameters[i]);
        }
        return objBuilder.ToString();
    }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900