Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Chương trình C# thay thế khoảng trắng bằng %20 (URL Encoding)

Phương thức string.Replace(oldValue, newValue) thay thế tất cả các lần xuất hiện của chuỗi con. Dùng để encode khoảng trắng thành %20 (chuẩn URL encoding).

Mã nguồn

using System;

class Demo {
    static void Main() {
        string str = "Hello World !";
        Console.WriteLine("Chuỗi gốc: " + str);
        
        // Thay thế tất cả khoảng trắng bằng %20
        string encoded = str.Replace(" ", "%20");
        
        Console.WriteLine("Chuỗi sau encode: " + encoded);
    }
}

Kết quả

Chuỗi gốc: Hello World !
Chuỗi sau encode: Hello%20World%20!

Mở rộng: URL Encoding hoàn chỉnh

Replace chỉ xử lý khoảng trắng. Để encode đúng chuẩn RFC 3986 (URL), dùng Uri.EscapeDataString hoặc WebUtility.UrlEncode:

using System;
using System.Web; // Cần reference System.Web.dll

string url = "https://example.com/search?q=c# programming";
string encoded = Uri.EscapeDataString(url);
// Kết quả: https%3A%2F%2Fexample.com%2Fsearch%3Fq%3Dc%23+programming

// Hoặc (ASP.NET Core)
using Microsoft.AspNetCore.WebUtilities;
string encoded = WebEncoders.UrlEncode(System.Text.Encoding.UTF8.GetBytes(url));

Giải mã (Decode)

string decoded = Uri.UnescapeDataString(encoded);
// Hoặc
string decoded = WebUtility.UrlDecode(encoded);

Lưu ý

  • Replace(" ", "%20") chỉ phù hợp cho case đơn giản (query param value).
  • Ký tự đặc biệt khác (&, =, ?, #, +...) cũng cần encode.
  • Uri.EscapeDataString encode tất cả ký tự trừ unreserved (A-Z, a-z, 0-9, -, ., _, ~).
  • WebUtility.UrlEncode encode space thành + (form encoding), Uri.EscapeDataString encode space thành %20.