C# Switch-case 字符串开头

发布于 2024-09-26 10:49:50 字数 406 浏览 2 评论 0原文

有没有什么方法可以在 switch 语句中设置 case 条件,在该条件中指定字符串是否以某些内容开头?

例如

Switch (mystring)
{
   case("abc")://String begins with abc (abcd or abc1 or abcz or abc.. or abc will fall in this condition).
      //Do Something
      break;
   default:
      break;
}

更新 其他字符串可以有不同的长度。

abc..abczyv

dcs2

qwerty

as...k

Is there any way to make a case condition in a switch statement where you say if a string begins with something?

ex

Switch (mystring)
{
   case("abc")://String begins with abc (abcd or abc1 or abcz or abc.. or abc will fall in this condition).
      //Do Something
      break;
   default:
      break;
}

UPDATE
Other strings can be different length.

abc..

abczyv

dcs2.

qwerty

as...k

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

A君 2024-10-03 10:49:50

如果您知道您关心的条件的长度都是相同的长度,那么您可以:

switch(mystring.substring(0, Math.Min(3, mystring.Length))
{
  case "abc":
    //do something
    break;
  case "xyz":
    //do something else
    break;
  default:
    //do a different thing
    break;
}

Math.Min(3, mystring.Length) 存在,因此小于 3 的字符串字符不会在子字符串操作上引发异常。

该技术有一些扩展,可以匹配例如一堆 2 字符字符串和一堆 3 字符字符串,其中先进行一些 2 字符比较匹配,然后再进行 3 字符比较。不过,除非您有大量此类字符串,否则对于正在运行的代码和必须维护它的人员来说,它很快就会变得比简单的 if-else 链接效率低。

编辑:添加,因为您现在已经声明它们将具有不同的长度。您可以执行我提到的检查第一个 X 字符,然后检查下一个 Y 字符等的模式,但是除非存在一种模式,其中大多数字符串的长度相同,否则维护起来既效率低下又可怕(典型的情况)过早悲观)。

另一个答案中提到了命令模式,因此我不会提供详细信息,就像将字符串模式映射到 ID 一样,但它们是选项。

我不会从 if-else 链更改为命令或映射模式来获得开关有时优于 if-else 的效率,因为您在命令比较或获取 ID 模式中会损失更多。如果它能让代码更清晰,我会这样做。

if-else 链可以很好地工作,无论是使用字符串比较还是使用正则表达式(如果你的比较比到目前为止的前缀匹配更复杂,后者可能会更简单、更快,我提到的是 reg- ex 只是因为它们有时确实可以很好地处理此类模式的更一般情况)。

如果您选择 if-else,请尝试考虑哪些情况最常发生,并让这些测试在不太常见的情况之前进行(当然,如果“以 abcd 开头”是要查找的情况,那么它会必须在“以 abc 开头”之前检查)。

If you knew that the length of conditions you would care about would all be the same length then you could:

switch(mystring.substring(0, Math.Min(3, mystring.Length))
{
  case "abc":
    //do something
    break;
  case "xyz":
    //do something else
    break;
  default:
    //do a different thing
    break;
}

The Math.Min(3, mystring.Length) is there so that a string of less than 3 characters won't throw an exception on the sub-string operation.

There are extensions of this technique to match e.g. a bunch of 2-char strings and a bunch of 3-char strings, where some 2-char comparisons matching are then followed by 3-char comparisons. Unless you've a very large number of such strings though, it quickly becomes less efficient than simple if-else chaining for both the running code and the person who has to maintain it.

Edit: Added since you've now stated they will be of different lengths. You could do the pattern I mentioned of checking the first X chars and then the next Y chars and so on, but unless there's a pattern where most of the strings are the same length this will be both inefficient and horrible to maintain (a classic case of premature pessimisation).

The command pattern is mentioned in another answer, so I won't give details of that, as is that where you map string patterns to IDs, but they are option.

I would not change from if-else chains to command or mapping patterns to gain the efficiency switch sometimes has over if-else, as you lose more in the comparisons for the command or obtaining the ID pattern. I would though do so if it made code clearer.

A chain of if-else's can work pretty well, either with string comparisons or with regular expressions (the latter if you have comparisons more complicated than the prefix-matches so far, which would probably be simpler and faster, I'm mentioning reg-ex's just because they do sometimes work well with more general cases of this sort of pattern).

If you go for if-elses, try to consider which cases are going to happen most often, and make those tests happen before those for less-common cases (though of course if "starts with abcd" is a case to look for it would have to be checked before "starts with abc").

攒一口袋星星 2024-10-03 10:49:50

现在可以通过 C# 7.0 的模式匹配来实现这一点。例如:

var myString = "abcDEF";

switch(myString)
{
    case string x when x.StartsWith("abc"):
        //Do something here
        break;
}

This is now possible with C# 7.0's pattern matching. For example:

var myString = "abcDEF";

switch(myString)
{
    case string x when x.StartsWith("abc"):
        //Do something here
        break;
}
梦开始←不甜 2024-10-03 10:49:50

简短的回答:不。

switch 语句采用的表达式仅计算一次。根据结果​​,执行另一段代码。

所以呢? => String.StartsWith 是一个函数。与给定参数一起,它是一个表达式。但是,对于您的情况,您需要为每种情况传递不同的参数,因此不能仅评估一次。

其他人已经给出了长答案#1。

长答案#2:

根据您想要实现的目标,您可能对命令感兴趣模式/责任链模式。应用于您的情况,每段代码都将由 Command 的实现来表示。除了execute方法之外,该命令还可以提供布尔Accept方法,该方法检查给定字符串是否以相应参数开头。

优点:代替硬编码的 switch 语句、硬编码的 StartsWith 计算和硬编码的字符串,您将拥有更多的灵活性。

您在问题中给出的示例将如下所示:

var commandList = new List<Command>() { new MyABCCommand() };

foreach (Command c in commandList)
{
    if (c.Accept(mystring))
    {
        c.Execute(mystring);
        break;
    }
}

class MyABCCommand : Command
{
    override bool Accept(string mystring)
    {
        return mystring.StartsWith("abc");
    }
}    

Short answer: No.

The switch statement takes an expression that is only evaluated once. Based on the result, another piece of code is executed.

So what? => String.StartsWith is a function. Together with a given parameter, it is an expression. However, for your case you need to pass a different parameter for each case, so it cannot be evaluated only once.

Long answer #1 has been given by others.

Long answer #2:

Depending on what you're trying to achieve, you might be interested in the Command Pattern/Chain-of-responsibility pattern. Applied to your case, each piece of code would be represented by an implementation of a Command. In addition to the execute method, the command can provide a boolean Accept method, which checks whether the given string starts with the respective parameter.

Advantage: Instead of your hardcoded switch statement, hardcoded StartsWith evaluations and hardcoded strings, you'd have lot more flexibility.

The example you gave in your question would then look like this:

var commandList = new List<Command>() { new MyABCCommand() };

foreach (Command c in commandList)
{
    if (c.Accept(mystring))
    {
        c.Execute(mystring);
        break;
    }
}

class MyABCCommand : Command
{
    override bool Accept(string mystring)
    {
        return mystring.StartsWith("abc");
    }
}    
不顾 2024-10-03 10:49:50

如果所有案例的长度相同,您可以使用
switch (mystring.SubString(0,Math.Min(len, mystring.Length)))
另一种选择是使用一个函数,该函数将根据字符串返回categoryId 并打开该id。

If all the cases have the same length you can use
switch (mystring.SubString(0,Math.Min(len, mystring.Length))).
Another option is to have a function that will return categoryId based on the string and switch on the id.

浅黛梨妆こ 2024-10-03 10:49:50

如果问题域具有某种字符串标头概念,则可以将其建模为枚举。

switch(GetStringHeader(s))
{
    case StringHeader.ABC: ...
    case StringHeader.QWERTY: ...
    ...
}

StringHeader GetStringHeader(string s)
{
    if (s.StartsWith("ABC")) return StringHeader.ABC;
    ...
}

enum StringHeader { ABC, QWERTY, ... }

If the problem domain has some kind of string header concept, this could be modelled as an enum.

switch(GetStringHeader(s))
{
    case StringHeader.ABC: ...
    case StringHeader.QWERTY: ...
    ...
}

StringHeader GetStringHeader(string s)
{
    if (s.StartsWith("ABC")) return StringHeader.ABC;
    ...
}

enum StringHeader { ABC, QWERTY, ... }
贩梦商人 2024-10-03 10:49:50

除了子字符串答案之外,您还可以将其作为 mystring.SubString(0,3) 并检查 case 语句是否为“abc”。

但在 switch 语句之前,您需要确保 mystring 的长度至少为 3。

In addition to substring answer, you can do it as mystring.SubString(0,3) and check in case statement if its "abc".

But before the switch statement you need to ensure that your mystring is atleast 3 in length.

╰ゝ天使的微笑 2024-10-03 10:49:50

尝试一下并告诉我它是否有效希望它对您有帮助:

string value = Convert.ToString(Console.ReadLine());

Switch(value)
{
    Case "abc":

    break;

    default:

    break;
}       

Try this and tell my if it works hope it help you:

string value = Convert.ToString(Console.ReadLine());

Switch(value)
{
    Case "abc":

    break;

    default:

    break;
}       
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文