savetext
is a string with a random length + "! Command1"
switch (savetext)
{
case savetext.EndsWith("! Command1"):
System.Diagnostics.Debug.WriteLine("Test1");
break;
case savetext.EndsWith("! Command2"):
System.Diagnostics.Debug.WriteLine("Test2");
break;
default:
System.Diagnostics.Debug.WriteLine(savetext)
break;
}
The output should be "Test1" but my method here is isnt working like I want. How can I fix this?
Since the suffix you're looking for always has the same length, you could extract it using Substring
, and then switch
on that:
String switcher = savetext.Substring(savetext.Length - 10);
switch (switcher)
{
case "! Command1":
System.Diagnostics.Debug.WriteLine("Test1");
break;
case "! Command2":
System.Diagnostics.Debug.WriteLine("Test2");
break;
default:
System.Diagnostics.Debug.WriteLine(savetext)
break;
}
A switch statement in C# 8:
var saveText = "111 ! Command1";
var logText = saveText switch
{
var x when x.EndsWith("! Command1") => "Test 1",
var x when x.EndsWith("! Command2") => "Test 2",
var x => x
};
System.Diagnostics.Debug.WriteLine(logText);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.