1

ユーザーからの入力をチェックして、ドットとダッシュのみを入力し、他の文字や数字を入力するとエラーメッセージが表示されることを確認したいと思います。また、ユーザーがスペースを入力できるようにしたかったのですが、変換時に空白を削除または無視するにはどうすればよいですか?

string permutations;
        string entered = "";
        do
        {
            Console.WriteLine("Enter Morse Code: \n");
            permutations = Console.ReadLine();
         .
         .
         } while(entered.Length != 0);

ありがとう!

4

2 に答える 2

3
string permutations = string.Empty;
Console.WriteLine("Enter Morse Code: \n");
permutations = Console.ReadLine(); // read the console
bool isValid = Regex.IsMatch(permutations, @"^[-. ]+$"); // true if it only contains whitespaces, dots or dashes
if (isValid) //if input is proper
{
    permutations = permutations.Replace(" ",""); //remove whitespace from string
}
else //input is not proper
{
    Console.WriteLine("Error: Only dot, dashes and spaces are allowed. \n"); //display error
}
于 2013-01-28T17:40:03.763 に答える
2

文字を1つのスペースで区切り、単語を2つのスペースで区切ると仮定します。次に、次のような正規表現を使用して、文字列が適切にフォーマットされているかどうかをテストできます。

bool ok = Regex.IsMatch(entered, @"^(\.|-)+(\ {1,2}(\.|-)+)*$");

正規表現の説明:
^文字列の先頭です。ドット(ドットは正規表現内で特別な意味を持つため、
\.|-エスケープされます)または( )マイナス記号です。残されたもの(ドットまたはマイナス)の1回以上の繰り返しを意味します。1つまたは2つのスペース(その後にドットまたはマイナスが続きます)。スペースに続いてドットまたはマイナスを0回以上繰り返します。行の終わりです。\|
+
\ {1,2}(\.|-)+
*
$

スペースで文字列を分割できます

string[] parts = input.Split();

2つのスペースは、空のエントリを作成します。これにより、単語の境界を検出できます。例えば

"–– ––– .–. ... .  –.–. ––– –.. .".Split();

次の文字列配列を生成します

{文字列[10]}
    [0]:「-」
    [1]:「–––」
    [2]:「.–。」
    [3]:「...」
    [4]:「。」
    [5]: ""
    [6]:「–.–。」
    [7]: " - -"
    [8]:「–..」
    [9]:「。」
于 2013-01-28T17:57:11.003 に答える