-2

In the example below I have a string with pipes | separating each segment in the string (ie:0123456789). What I am trying to do is replace the pipe character with a string as shown in the example below. How do I accomplish that?

From what I understand the .Replace can only support (char,char) or (string, string).

Example code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleProject
{
    public class Program
    {
        public static void Main(string[] args)
        {
            String val1 = "0123456789|0123456789|0123456789|0123456789|0123456789";
            val1.Replace('|'.ToString(), "*val1TEST*");
            String val2 = "0123456789|0123456789|0123456789|0123456789|0123456789";
            val2.Replace("|", "**val2Test**");
            Console.WriteLine(String.Format("{0}{1}","val1: ",val1));
            Console.WriteLine(String.Format("{0}{1}", "val2: ", val2));
        }
    }
}

Output From Console

val1: 0123456789|0123456789|0123456789|0123456789|0123456789

val2: 0123456789|0123456789|0123456789|0123456789|0123456789
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Isaac
  • 61
  • 2
  • 9
  • 2
    assign it back `val1 = val1.Replace('|'.ToString(), "*val1TEST*");` strings are immutable. – Habib Oct 07 '14 at 16:03
  • and also http://stackoverflow.com/questions/1948978/string-replace-not-working – Habib Oct 07 '14 at 16:04
  • As Habib correctly said, strings are immutable. This means you cannot change the object it self. but you can change the value it references. val1 = val1.Replace(.....), will change the value val1 references. – Kristian Nissen Oct 07 '14 at 16:22

2 Answers2

6

If you look at the definition for .Replace() it returns a string - so you need to set it to a variable like so:

val1 = val1.Replace('|'.ToString(), "*val1TEST*");
entropic
  • 1,683
  • 14
  • 27
  • Thanks for looking at this post, I forgot to set it to a variable. I'm going to accept this as the answer. – Isaac Oct 07 '14 at 16:06
1

The problem you are having is that Replace() returns a string. It doesn't modify the existing string. You need to set the strings to the return value:

str = str.Replace(...);

Furthermore, a string with one character is the same as a single character, which is why there is no Replace(char, string).

siride
  • 200,666
  • 4
  • 41
  • 62