D 語言入門指南/條件語句和迴圈/Switch 語句
外觀
switch 語句幾乎存在於所有程式語言中,它通常用於檢查多個條件。語法與 C++ 或 Java 中的語法相同。它具有以下形式
switch(variable)
{
case value_to_check:
statements;
break;
default:
statements;
}
以下是一些簡單的示例
import std.stdio,
std.string : strip;
void main()
{
// Command that user want to launch
string input;
write("Enter some command: ");
// Get input without whitespaces, such as newline
input = strip(readln());
// We are checking input variable
switch( input )
{
// If input is equals to '/hello'
case "/hello":
writeln("Hello!");
break;
// If it is equals to '/bye'
case "/bye":
writeln("Bye!");
break;
// None of specified, unknown command
default:
writeln("I don't know that command");
}
}
我們程式碼的結果
Enter some command: /hello Hello!
請注意每個 case 後的 break 關鍵字!如果它被繞過,它後面的每個 case 都會被呼叫。因此,如果沒有 break,程式碼的控制檯輸出如下
Enter some command: /hello Hello! Bye! I don't know that command
如你所見,/hello 之後的每個 case 都被“呼叫”了,如果我們想要在多個 case 中呼叫相同的語句,這將非常有用。以下是一個額外的示例
string cmd = "/hi";
switch( cmd )
{
case "/hi":
case "/hello":
case "/wassup":
writeln("Hi!");
break;
// ...
}