LoginSignup
9
5

More than 5 years have passed since last update.

[C#] 文字列を空白で分割する(複数指定, 連続空白, 半角/全角空白対応)

Posted at

WPFで検索バーを実装する際に半角/全角空白で分割する指定方法が必要だったのでメモ

基本的に string.Split() を使用すれば良いです。
連続空白の場合の対応として、データがない場合を無視する StringSplitOptions.RemoveEmptyEntries オプションを使用します。

さすがにユニコード空白は考えないことにしてますが必要なら足してください。

実装例

サンプル
using System;

namespace hwapp
{
    class Program
    {
        static void Main(string[] args)
        {
            // 半角空白, 連続半角空白, 全角空白, 連続全角空白
            var text = "hoge foo  bar Hoge  Foo";

            SplitFunc1(text);
            SplitFunc2(text);
        }

        private static void SplitFunc1(string text)
        {
            var words = text.Split(new string[] { " ", " " }, StringSplitOptions.RemoveEmptyEntries);

            foreach (var word in words)
            {
                Console.WriteLine($"[1] {word}");
            }
        }

        private static void SplitFunc2(string text)
        {
            var words = text.Split(new char[] { ' ', ' ' }, StringSplitOptions.RemoveEmptyEntries);

            foreach (var word in words)
            {
                Console.WriteLine($"[2] {word}");
            }
        }
    }
}
実行結果
[1] hoge
[1] foo
[1] bar
[1] Hoge
[1] Foo
[2] hoge
[2] foo
[2] bar
[2] Hoge
[2] Foo

参考

StringSplitOptions 列挙型 (System)

9
5
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
5