【问题标题】:string manipulation in c# arrayindex out of range exception why it is occur?c#arrayindex中的字符串操作超出范围异常为什么会发生?
【发布时间】:2018-06-24 16:27:36
【问题描述】:
using System.IO;
using System;

class Program
{
    static void Main()
    {
        string s1="iamamamok";
        string s2="mam";
        int i=0,j=0;
        int count=0,countchar=0;

        while(j<s2.Length)
        {
            while(i<s1.Length)
            {
                if(s1[i]==s2[j])
                {
                    countchar++;
                    j++;
                    if(countchar==(s2.Length))
                    {
                        count +=1;
                        j=0;
                        countchar=0;
                    }

                }
                else
                {
                    j=0;
                    countchar=0;
                }
                i++;
                if(i==s1.Length)
                {
                    break;
                }
            }
        }
    Console.Write(count);

    }
}

当我尝试运行此代码时,它会使数组索引超出范围,但我尝试涵盖这些字符串的所有可能情况,请解释为什么会发生此错误??????????????? ????????????????????????????????????

【问题讨论】:

  • 你能说明你想让你的程序做什么吗?
  • 因为您的代码不是有问题的代码此代码陷入无限循环。

标签: c# string substring indexoutofboundsexception


【解决方案1】:

你在你的内部循环中增加j,然后再次使用它而不检查它是否小于字符串的长度。

(以备日后参考,请贴出错误信息,包括错误发生的行,以帮助其他人调试)

【讨论】:

  • 这个程序运行到无限循环而不是索引超出范围异常
猜你喜欢
  • 2014-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-23
  • 1970-01-01
相关资源
最近更新 更多