C#で、連続する空白文字を単一のスペースに置き換えます
この投稿では、C#で連続する空白文字を単一のスペースに置き換える方法について説明します。
C#の空白は、スペース文字で構成されます ' '
、水平タブ \t
、キャリッジリターン \r
、ラインフィード \n
、など。
1.正規表現の使用
正規表現 \s
あらゆる種類の空白文字と一致します。正規表現でこのパターンを使用すると、連続する空白を単一のスペースに置き換えることができます。次のコード例は、入力文字列の連続する空白文字を単一のスペース文字列に置き換える方法を示しています。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
using System; using System.Text.RegularExpressions; public static class Extensions { private static readonly Regex regex = new Regex(@"\s+"); public static string ReplaceWhiteSpaces(this string str) { return regex.Replace(str, " "); } } public class Example { public static void Main() { string str = @"Techie Delight!!"; string s = str.ReplaceWhiteSpaces(); Console.WriteLine(s); } } /* 出力: Techie Delight!! */ |
2.使用する String.Split()
方法
使用することもできます String.Split()
あらゆる種類の空白文字を単一のスペースに置き換える方法。空白文字を区切り文字として使用して文字列を分割し、空でないシーケンスを単一のスペースで結合するという考え方です。次のコード例は、これを実装する方法を示しています。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
using System; public static class Extensions { public static string ReplaceWhiteSpaces(this string str) { char[] whitespace = new char[] { ' ', '\t', '\r', '\n'}; return String.Join(" ", str.Split(whitespace, StringSplitOptions.RemoveEmptyEntries)); } } public class Example { public static void Main() { string str = @"Techie Delight!!"; string s = str.ReplaceWhiteSpaces(); Console.WriteLine(s); } } /* 出力: Techie Delight!! */ |
3.LINQの使用
上記のアプローチと同様に、区切り文字として空白文字を使用して文字列を分割し、LINQを使用して空でないシーケンスをフィルタリングします。次に、空でないシーケンスを単一のスペースで結合します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
using System; using System.Linq; public static class Extensions { public static string ReplaceWhiteSpaces(this string str) { char[] delims = new char[] { ' ', '\t', '\r', '\n'}; return String.Join(" ", str.Split(delims).Where(s => !String.IsNullOrWhiteSpace(s))); } } public class Example { public static void Main() { string str = @"Techie Delight!!"; string s = str.ReplaceWhiteSpaces(); Console.WriteLine(s); } } /* 出力: Techie Delight!! */ |
これで、C#で連続する空白文字を単一のスペースに置き換えることができます。
こちらも参照: