Search code examples
c#stringreplacestring-formattingstringbuilder

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.

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