2017-06-14 44 views
0

我只想问如何检查n拆分字符串是否存在或不存在?如何检查n拆分字符串是否存在(C#)

对于例如: 输入是一个文本框和我把一个文本在文本框“您好”

var TEXTS = input.Text.Split(' '); 

我们认为知道结果是: 文章[0] =“喜” 案文[1] =“there”

我想检查TEXTS [1]是否存在?

我只是试过这样,但它不工作。

if (TEXTS[1]!=null) { 

} 
+0

TEXTS.Length> = 2 –

回答

1

可以检查数组的索引通过使用以下代码存在:

int index = 25 ; //input any number here 

if(index < array.Length) 
{ 
    //it exists 
} 
+0

谢谢。它简单,正是我想要的。 – Fachri

0

需要检查像阵列的长度:

if (TEXTS.Length > 1) { } 
+0

这是一个正确的实现;然而'1'是一个魔法值,因此很难消化。 “TEXTS.Length> = 2”是,恕我直言,稍微好一点的选择:当我们想要'2'项目时,我们与'2'比较。 –

0

可以使用foreach得到每个值

var TEXTS = input.Text.Split(' '); 
foreach (string val in TEXTS) 
{ 
//you can use val 
} 

,或者您可以为您for让每个值

var TEXTS = input.Text.Split(' '); 
for (int i = 0; i < TEXTS.Length; i++) 
{ 
//you can use TEXTS[i] 
} 

我希望它帮你。

0

您还可以通过使用System.Linq命名空间获得与其他答案相同的结果,以获得稍微好看的语法。

if (TEXTS.ElementAtOrDefault(1) != null){ 
    Console.Write("IT EXISTS!!"); 
} 
+0

'TEXTS [0] .Any()'实际上意味着'TEXTS [0]'字符串*不为空*;或者把它放在不同的位置,'input.Text' *无法启动*与空间 –

+0

是的 - 这就是我们想要的不是吗? – DNKROZ

+0

“我想检查TEXTS [1]是否存在?”它可以被视为“文本至少有2个项目”(我的解释,即我们可以*安全地* *文本[1] * * *)或如果你想要“文本[1]不是空的”;在这种情况下,请注意索引:'1' –

0

如果你想检查只,你所要做的就是计数分离(空格,在上下文中):

int count = 2; // we want to ensure at least 2 items 

bool result = input 
    .Text 
    .Where(c => c == ' ') 
    .Skip(count - 2) 
    .Any(); 

if (result) { 
    // we have at least count - 1 spaces, and thus at least count parts 
} 

如果你想分裂检查,尝试使用Length

int count = 2; // we want to ensure at least 2 items 

string[] items = input 
    .Text 
    .Split(' '); 

if (items.Length >= count) { 
    // we have at least count items, and thus can put items[0] ... items[count - 1] 
} 
相关问题