Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C# program to replace all spaces in a string with '%20'
When working with strings in C#, you may need to replace spaces with '%20' for URL encoding or other formatting purposes. The Replace() method provides a simple way to substitute all occurrences of a character or substring with another value.
Syntax
Following is the syntax for using the Replace() method −
string newString = originalString.Replace(oldValue, newValue);
Parameters
oldValue − The string or character to be replaced
newValue − The string or character to replace with
Return Value
The method returns a new string with all occurrences of the specified value replaced. The original string remains unchanged since strings are immutable in C#.
Example
Following example demonstrates how to replace all spaces in a string with '%20' −
using System;
class Demo {
static void Main() {
string str = "Hello World !";
Console.WriteLine("Original String: " + str);
string str2 = str.Replace(" ", "%20");
Console.WriteLine("String (After replacing): " + str2);
}
}
The output of the above code is −
Original String: Hello World ! String (After replacing): Hello%20World%20!
Using Replace() for URL Encoding
Replacing spaces with '%20' is commonly used in URL encoding. Here's a more practical example −
using System;
class URLEncoder {
static void Main() {
string[] urls = {
"My Document.pdf",
"Hello World Page.html",
"User Profile Settings.aspx"
};
Console.WriteLine("URL Encoding Examples:");
Console.WriteLine("----------------------");
foreach (string url in urls) {
string encodedUrl = url.Replace(" ", "%20");
Console.WriteLine("Original: " + url);
Console.WriteLine("Encoded: " + encodedUrl);
Console.WriteLine();
}
}
}
The output of the above code is −
URL Encoding Examples: ---------------------- Original: My Document.pdf Encoded: My%20Document.pdf Original: Hello World Page.html Encoded: Hello%20World%20Page.html Original: User Profile Settings.aspx Encoded: User%20Profile%20Settings.aspx
Multiple Character Replacement
You can also replace multiple types of characters by chaining Replace() methods −
using System;
class MultipleReplace {
static void Main() {
string text = "Hello World! How are you?";
Console.WriteLine("Original: " + text);
string encoded = text.Replace(" ", "%20")
.Replace("!", "%21")
.Replace("?", "%3F");
Console.WriteLine("Encoded: " + encoded);
}
}
The output of the above code is −
Original: Hello World! How are you? Encoded: Hello%20World%21%20How%20are%20you%3F
Conclusion
The Replace()
