How do I replace all the spaces with in C#?

2020-01-24 12:11发布

I want to make a string into a URL using C#. There must be something in the .NET framework that should help, right?

标签: c# url urlencode
10条回答
Emotional °昔
2楼-- · 2020-01-24 12:19

I found useful System.Web.HttpUtility.UrlPathEncode(string str);

It replaces spaces with %20 and not with +.

查看更多
▲ chillily
3楼-- · 2020-01-24 12:22

I believe you're looking for HttpServerUtility.UrlEncode.

System.Web.HttpUtility.UrlEncode(string url)
查看更多
小情绪 Triste *
5楼-- · 2020-01-24 12:26

To properly escape spaces as well as the rest of the special characters, use System.Uri.EscapeDataString(string stringToEscape).

查看更多
叛逆
6楼-- · 2020-01-24 12:28

I needed to do this too, found this question from years ago but question title and text don't quite match up, and using Uri.EscapeDataString or UrlEncode (don't use that one please!) doesn't usually make sense unless we are talking about passing URLs as parameters to other URLs.

(For example, passing a callback URL when doing open ID authentication, Azure AD, etc.)

Hoping this is more pragmatic answer to the question: I want to make a string into a URL using C#, there must be something in the .NET framework that should help, right?

Yes - two functions are helpful for making URL strings in C#

  • String.Format for formatting the URL
  • Uri.EscapeDataString for escaping any parameters in the URL

This code

String.Format("https://site/app/?q={0}&redirectUrl={1}", 
  Uri.EscapeDataString("search for cats"), 
  Uri.EscapeDataString("https://mysite/myapp/?state=from idp"))

produces this result

https://site/app/?q=search%20for%20cats&redirectUrl=https%3A%2F%2Fmysite%2Fmyapp

Which can be safely copied and pasted into a browser's address bar, or the src attribute of a HTML A tag, or used with curl, or encoded into a QR code, etc.

查看更多
祖国的老花朵
7楼-- · 2020-01-24 12:33

The below code will replace repeating space with a single %20 character.

Example:

Input is:

Code by Hitesh             Jain

Output:

Code%20by%20Hitesh%20Jain

Code

static void Main(string[] args)
{
    Console.WriteLine("Enter a string");
    string str = Console.ReadLine();
    string replacedStr = null;

    // This loop will repalce all repeat black space in single space
    for (int i = 0; i < str.Length - 1; i++)
    {
        if (!(Convert.ToString(str[i]) == " " &&
            Convert.ToString(str[i + 1]) == " "))
        {
            replacedStr = replacedStr + str[i];
        }
    }
    replacedStr = replacedStr + str[str.Length-1]; // Append last character
    replacedStr = replacedStr.Replace(" ", "%20");
    Console.WriteLine(replacedStr);
    Console.ReadLine();
}
查看更多
登录 后发表回答