查找字符串是否为空

时间:2019-07-18 11:04:14

标签: c# string

我有作业要做,并且我有一个像这样初始化的字符串:

string s= "abc,def,ghi,jkl,mno,,";

我必须检查逗号附近是否存在字符或没有任何字符。我已经尝试过此代码:

do{
    if (s==','){
        count++;
        if (count==3)
            if(s++!=',')
                MessageBox.Show("Substring not empty");
            else
                MessageBox.Show("Substring empty");
    }
}while(!String.IsNullOrEmpty(s));

但是我有两个错误:

Error   1   Operator '==' cannot be applied to operands of type 'string' and 'char'
Error   2   Operator '++' cannot be applied to operand of type 'string' 

那么,如何验证逗号后是否有字符?

3 个答案:

答案 0 :(得分:4)

好吧,这是家庭作业,所以像LINQ这样的“高级”东西不是我上交的:

var somethingIsEmpty = str.Split(',').Any(e => e.Length==0);

再考虑一下,写一些注释,并在其下写代码:

//get the string 

//split the string on commas, don't enable RemoveEmptyEntries

//use a loop to iterate through the whole splitted array

  //if any element of the array has a zero length, show a message

学习时,这是一种更好的编码方式;用您想到的语言编写算法,作为注释。。然后将注释翻译为代码,最后得到注释良好的代码,就可以了。不写评论意味着您冒着忘记去往哪里,正在做什么,算法是什么的风险,并且由于尝试和错误而回到编码而不考虑自己的实际情况

已经在注释中编写了算法,我可以像这样轻松地将代码翻译为:

//get the string
string str = "a,b,c,,d";

//split the string on commas, don't enable RemoveEmptyEntries
string[] bits = string.Spilt(',');

//use a loop to iterate through the whole splitted array
for(int i = 0; i <= bits.Length; i++){

  //if any element of the array has a zero length, show a message
  if(bits[i].Length > 0)
    MessageBox.Show("Element " + i + " has zero length");
}

此代码包含三个故意的错误。我不想剥夺您应该在这里获得的学习机会;您仍然需要考虑这一点-不仅要提交此代码-仔细研究,思考并解决错误

或者从德米特里(Dmitry)的评论中,进行以下调查:

yourstring.Contains(",,");
yourstring.StartsWith(",");
yourstring.EndsWith(",");

这些返回布尔值,如果其中任何一个为true,则说明您的字符串不符合规范

答案 1 :(得分:2)

awaitAll->是一个字符

'a'->是一个字符串

此错误消息非常清楚。

  • 错误1运算符'=='无法应用于类型为'string'和'char'的操作数
  • -> s 是字符串变量但是','是一个char值。你不能比较这两个

  • 错误2运算符'++'无法应用于类型为'string'的操作数
  • -> content 变量在哪里? 内容是数字值吗?

    此代码无效。

    请尝试这个

    "a"

    输出

    string s = "abc,def,ghi,jkl,mno,,";
    
            string[] s2 = s.Split(',');
    
            for (int i = 0; i < s2.Length; i++)
            {
                if (!string.IsNullOrEmpty(s2[i]))
                    Console.WriteLine("{0} Partition FULL",i.ToString());
                else
                    Console.WriteLine("{0} Partition Empty", i.ToString());
            }
    
    
            Console.Read();
    

    答案 2 :(得分:1)

    第一个错误sstring。当您执行s==','时,您正在将stringchar进行比较,因为','char

    第二个错误:您无法将++运算符应用于string。您应该以与访问string中的项目相同的方式访问array的单个字符(s[0]将获得第一个字符,依此类推。)

    两个问题的解决方案:初始化一个int计数器,并使用它通过string和{{1}逐个字符地遍历i++ }。

    这是一个简短的摘要:

    s[i]