0

I am having string variable as follow

 string pctSign = "\0\0\0";

I want to replace first two characters with "%"

i.e. Final o/p:- pctSign="%\0\0";

How to do this with String.Replace?

Dennis Traub
  • 50,557
  • 7
  • 93
  • 108
Amol Kolekar
  • 2,307
  • 5
  • 30
  • 45
  • Try using `Substring` (possibly in combination with `IndexOf`) instead. – Chris Sinclair Sep 11 '12 at 11:18
  • possible duplicate of [How do I replace the *first instance* of a string in .NET?](http://stackoverflow.com/questions/141045/how-do-i-replace-the-first-instance-of-a-string-in-net) – Paolo Moretti Sep 11 '12 at 11:20

4 Answers4

5
// Option 1
var result = "%" + pctSign.Remove(0, 2);

// Option 2
var result = "%" + pctSign.Substring(2);

// Option 3
var regex = new Regex("^\\0");
var result = regex.Replace(pctSign, "%");

If you absolutely want to user String.Replace() then you can write your own extension method:

public static class StringExtension
{
    public static String Replace(this string self, 
                                      string oldString, string newString, 
                                      bool firstOccurrenceOnly = false)
    {
        if ( !firstOccurrenceOnly )
            return self.Replace(oldString, newString);

        int pos = self.IndexOf(oldString);
        if ( pos < 0 )
            return self;

        return self.Substring(0, pos) + newString 
               + self.Substring(pos + oldString.Length);
    }
}

// Usage:
var result = pctSign.Replace("/0", "%", true);
Dennis Traub
  • 50,557
  • 7
  • 93
  • 108
2

Try this:

var pctSign = "\0\0\0";
var result = string.Format("%{0}", pctSign.Substring(2));
Spontifixus
  • 6,570
  • 9
  • 45
  • 63
0
string s = pctSign.Substring(2, pctSign.Length);
s = "%" + s;
Roshana
  • 428
  • 3
  • 15
0

you mean only first two then

pctSign = "%"+pctSign.substring(2);
dnyan86
  • 107
  • 2
  • 2
  • 8