I have an String that is entered by the end user, and this string should be of the format Showing {0} to {1} of {2}
and I would like to replace the parameters in curly brackets with numbers that I compute from the backend.
Exactly like it happens for the strings from the properties file.
How can I do that?
Sample input:
Showing {0} to {1} of {2}
Sample output:
Showing 1 to 12 of 30
C# | Replace() Method. In C#, Replace() method is a string method. This method is used to replace all the specified Unicode characters or specified string from the current string object and returns a new modified string. This method can be overloaded by passing arguments to it.
But in our example, to add a parameter to a string , we are going to use an overload that has two string parameters: public string Replace (string oldValue, string newValue); public string Replace (string oldValue, string newValue);
You can do this with MessageFormat
:
String userInput = "Showing {0} to {1} of {2}";
String result = MessageFormat.format(userInput, 1, 12, 30);
You can use String.format()
Here is how to do that
int a = 1;
int b = 12;
int c = 30;
String myFormattedString = String.format("Showing %d to %d of %d", a, b, c);
// Value of myFormattedString is 'Showing 1 to 12 of 30'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With