12 out of 15 rated this helpful - Rate this topic

String.Replace Method

Returns a new string in which all occurrences of a specified Unicode character or String in the current string are replaced with another specified Unicode character or String.

This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.

  Name Description
Public method Replace(Char, Char) Returns a new string in which all occurrences of a specified Unicode character in this instance are replaced with another specified Unicode character.
Public method Replace(String, String) Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.
Top
Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
String Replace como mascara

public static string FormatCNPJ(this string cnpj)
{

if (cnpj.Length == 14)
{ //00.000.000/0000-00
cnpj = cnpj.Substring(0, 2) + "." + cnpj.Substring(2, 3) + "." + cnpj.Substring(5, 3) + "/" + cnpj.Substring(8, 4) + "-" + cnpj.Substring(12, 2);
}
return cnpj;
}
String.Replace returns a new string
string test = "mystring1";

Writing test.Replace("1","2"); won't work because test.Replace(string, string); is a method which returns a new string, and does not modify the original string, and so it must be captured and used the set the original string.

You must write:
test = test.Replace("1","2")

// test now equals "mystring2".