有没有办法将 switch 与 String.contains("") 集成?

编程入门 行业动态 更新时间:2024-10-27 07:23:50
本文介绍了有没有办法将 switch 与 String.contains("") 集成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要检查 String 对象是否包含 () 各种子字符串,并根据结果执行不同的代码段.目前我有一系列 else if.如果可能,我想将其转换为开关.有没有办法做到这一点?

I need to check if a String object contains() various substrings and based on the results have different pieces of code execute. Currently I have a series of else if. I would like to convert it into a switch if possible. Is there a way to do this?

目前:

if (SomeString.contains("someSubString")) { . . . do something } else if (SomeString.contains("anotherSubString")) { . . . do something else } else if (SomeString.contains("yetanotherSubString")) { . . . do something even more different } . . .

推荐答案

当我遇到这样的情况,实在不想用else if时,我会这样做:

When I have a situation like this, and really don't want to use else if, I do something like this:

String[] cases = {"someSubString", "anotherSubString", "yetanotherSubString"}; int i; for(i = 0; i < cases.length; i++) if(SomeString.contains(cases[i])) break; switch(i) { case 0: //someSubString System.out.println("do something"); break; case 1: //anotherSubString System.out.println("do something else"); break; case 2: //yetanotherSubString System.out.println("do something even more different"); break; default: System.out.println("do nothing"); }

当然,这有几个缺点.首先,如果您在除末尾之外的任何地方添加另一个字符串,所有索引都会发生变化,您必须手动进行更正.尽管如此,我认为我已经使用过一两次这样的东西,并认为它使代码更具可读性.据推测,索引在程序中具有某种意义,因此以对问题有意义的方式耦合了 0...someSubString.

Of course, that has a couple of downsides. For starters, if you add another strings anywhere but the end, all the indices will shift, and you have to correct for that manually. Still, I think I have used something like that once or twice and thought it makes the code more readable. Presumably, the indices had some meaning in the program, thus coupling the 0...someSubString in a way meaningful to the problem.

更多推荐

有没有办法将 switch 与 String.contains("") 集成?

本文发布于:2023-10-31 01:30:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1544594.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:没有办法   switch   quot   String

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!