c#.NET and sprintf syntax
Check out string.Format and here is a version of your code using it:
string output = "The user {0} logged in";
string loggedIn = "is";
string loggedOut = "isn't";
if (TheUser.CheckStatus())
{
output = string.Format(output, loggedIn);
}
else
{
output = string.Format(output, loggedOut);
}
return output;
Or more simply: (using a ternary expression)
string output = "The user {0} logged in";
return TheUser.CheckStatus()
? string.Format(output, "is")
: string.Format(output, "isn't");
If you want to stick with %s,%d....
string sprintf(string input,params object[] inpVars)
{
int i=0;
input=Regex.Replace(input,"%.",m=>("{"+ i++/*increase have to be on right side*/ +"}"));
return string.Format(input,inpVars);
}
You can now do
sprintf("hello %s..Hi %d","foofoo",455);
The whole printf
family of functions in C is replaced by String.Format. The same interface is also exposed in for example Console.WriteLine()
.
string output = "The user {0} logged in";
string loggedIn = "is";
string loggedOut = "isn't";
output = string.Format(output, loggedIn);
With C# 6 you can use the formattable string:
if (TheUser.CheckStatus())
{
output = $"The user {loggedIn} logged in"
}
The {loggedIn}
inside the string is the variable name that you have defined.
Also, you have intellisense inside the curly braces to pick the variable name.