Multiple string replacements...

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Samishii23
    New Member
    • Sep 2009
    • 246

    Multiple string replacements...

    I know this is simple. Have a small to large string. Replace a 'Key' within that string with what I want replaced... Heres a small example, then the issue I'm having in my head...

    Code:
    /* One replacement string */
    string replace = "Increases your attack power by ~R~ for every 180 armor value you have.";
    string[] replace_with = new string[] { "1","2","3","4","5" };
    Based on user input, it would be either of the 5. But. Rather then storing 5 full string variables, I'd like to just replace the value in the string.
    I know that this would be the best piece of code for the single replacement...
    Code:
    replace.Replace("~R~", replace_with[user_select]);
    Heres my problem:
    I will often have the case where I may need more then 1 Replacement in the string. How do I go about this? =\
  • tlhintoq
    Recognized Expert Specialist
    • Mar 2008
    • 3532

    #2
    Take a look at string.format

    Code:
    int factor = 3;
    int Points = 180;
    string Device = "Armor";
    string replace = string.format("Increases your attack power by {0}, for every {1} {2} value you have.", factor.ToString(), Points.ToString(), Device);
    The placeholders {0}, {1}, {2} will be replaced with factor, Points and Device giving you a final string of:

    "Increases your attack power by 3 for every 180 Armor value you have."

    Comment

    • GaryTexmo
      Recognized Expert Top Contributor
      • Jul 2009
      • 1501

      #3
      While I agree with tlhintoq's answer, it's worthwhile to point out that sometimes there are... issues... with string.Format. Don't get me wrong, it's my favourite thing in the world at times, but other times it gets you with formatting. In most simple cases (such as your case) it is exactly what you need. Sometimes, when you want to get fancy, you can confuse it (generally when you are trying to build replacement strings to be used by other replacement strings).

      The alternative method is to just simply do something like...
      Code:
      string part1 = "You got ";
      string part2 = " points for hitting ";
      string part3 = " targets!";
      string final = part1 + points.ToString() + part2 + targetsHit.ToString() + part3;
      Or something to that effect (ie, manually building the string). Again, tlhintoq's method is much easier to deal with and generally better in 99% of cases, but I wanted to point out the alternative since I have ran into it a few times :)

      Comment

      Working...