如何从逗号分隔的字符串中查找给定的文本是否可用. [英] How to find whether a given text is avilable from comma separated string.
问题描述
嗨
我有一个字符串,其中所有系统名称均以逗号分隔.
示例:
Hi
I have a string which has all the system names in a comma separated form.
Example:
string systemNames="system1,system2,system3,system4";
从此字符串中,我需要找到一个系统名称,无论该系统名称是否存在.
例如
From this string I need to find a system name whether the system name exists or not.
For example
I give "system1 " I should get as "TRUE"<br />
I give "system10" I should get as "False"<br />
请帮助我解决此问题,该代码应具有任何循环.
Kindly Help me to solve this , The code should have any Loop.
推荐答案
private bool SystemExists(string systemName)
{
text = text.Trim().ToLower();
string[] parts = systemNames.Split(',');
int count = (from part in parts
where part.Trim().ToLower() == systemName
select part).Count();
return (count > 0);
}
如果要区分大小写,只需删除对string.ToLower()
的调用.
编辑===========
为什么将此票选为1?这是正确的,并且可以满足OP的规定需求.
If you want it to be case-sensitive, just remove the calls to string.ToLower()
.
EDIT ===========
Why was this voted a 1? It''s correct, and fulfills the stated needs of the OP.
如果字符串的模式保持不变,则可以使用以下代码:
If the pattern of the string remains the same, you cna use this:
string inputValue = originalInput + ",";
bool result = systemNames.ToUpper().Contains(inputValue.ToUpper());
我不确定Contains方法是否有任何IgnoreCase重载.如果有,您可以使用它.您还可以在任何需要的地方进行修整.
I am not sure if there is any IgnoreCase overload for the Contains method. If there is, you can use that. You can also do trimming wherever needed.
使用如下所示的拆分功能:
Use split function like this :
string systemNames = "system1,system2,system3,system4";
String[] arr = systemNames.Split(',');
String mySystemName="System1";
foreach(String system in arr)
{
if(system.Equals(mySystemName))
{
//You have found the system
}
}
希望能有所帮助! :)
Hope it helped! :)
这篇关于如何从逗号分隔的字符串中查找给定的文本是否可用.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!