Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parametrize a string and replace parameters

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
like image 590
cloudy_weather Avatar asked Mar 11 '15 10:03

cloudy_weather


People also ask

How to replace parameters in string c#?

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.

How to add parameter value in a string in c#?

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);


Video Answer


2 Answers

You can do this with MessageFormat:

String userInput = "Showing {0} to {1} of {2}";
String result = MessageFormat.format(userInput, 1, 12, 30);
like image 54
Duncan Jones Avatar answered Oct 19 '22 09:10

Duncan Jones


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'
like image 26
Davide Lorenzo MARINO Avatar answered Oct 19 '22 09:10

Davide Lorenzo MARINO