在 C# 中去除字串的前後空格
若要使用 C# 來去除字串的前後空格,請使用正則表示式。
首先,為正則表示式設定模式:
string pattern = "\s+";
比如說我們的字串的前後有空格,如下所示:
string input = " Welcome User ";
現在使用正則表示式來設定模式,然後使用 C# 將結果放入到一個新的字串當中。
Regex rgx = new Regex(pattern); string result = rgx.Replace(input, replacement);
以下為完整的示例:
示例
using System;
using System.Text.RegularExpressions;
namespace Demo {
class Program {
static void Main(string[] args) {
string input = " Welcome User ";
string pattern = "\s+";
string replacement = " ";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);
Console.WriteLine("Original String: {0}", input);
Console.WriteLine("Replacement String:{0}", result);
Console.ReadKey();
}
}
}
廣告
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP