简体   繁体   中英

Should we use String.format or String.replace in C#?

we are trying to create a app that shows the user messages. Here are some example messages:

  • "You have an offer for {PlayerName} from {Offerclub}. They would pay {Offer}".
  • "{Offerclub} would like to buy {Playername} for {Offer}".

We are getting these strings from our database. (Our first attempt was to make a class, with different functions, that gave us back the strings. We used string interpolation. Then we realized that this is no good option, because the users can't create contents/strings by themselves and we have to update our app every time we create a few more strings in this class.)

The options we know:

  1. String.format: something like that:

    string result = string.Format("{1} blalbal...- {2}blabla... {3}", value1, value2, value3);

The problem here: We want to use strings with different positions of the input like in our examples. Sometimes the first one is the playername, sometimes it is the clubname...

  1. String.replace: We thought about fixed placeholder names and would then use replace to make our changes.
  2. String Builder: We thought to simply concenate our strings. We would first read them from the database and use String.split to create an array of the strings.

Questions:

  • Are there better options? (We are talking about some messages. Maybe a few hundred messages in the worst case) We would prefer to use String.replace because it sounds like the easiest solution.

You can simply store the string format in the database, the order of the variables doesn't need to be consistent?

SQL Database

"You have an offer for {0} from {1}. They would pay {2}."
"{1} would like to buy {0} for {2}."

You could even leave out arguments if you wanted.

"{1} would like to buy {0}, they would like to discuss pricing."

c#

string format = GetStringFromDatabase(someIdentifier);
string message = String.Format(format, PlayerName, Offerclub, Offer);

There's a better and easy way to make those strings. You can try using this example:

string result = $"{value1} blalbal...- {value2}blabla... {value3}";

This "$" symbol allows you to insert the variables directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM