C# UnhandHold异常:System.Indexoutofbound异常:索引超出数组的界限

C# UnhandHold异常:System.Indexoutofbound异常:索引超出数组的界限,c#,C#,我正在尝试编写从字符串中拆分第一个字符的代码,如: 输入为=这是Stackoverflow 输出(我想要的)=TIS 但是我得到了unhandhold异常:System.Indexoutofbound异常:索引超出了数组的界限 //我的代码是 using System; public class n2 { public static void Main(String[] args) { String s1; Console.WriteLine(

我正在尝试编写从字符串中拆分第一个字符的代码,如: 输入为=
这是Stackoverflow
输出(我想要的)=
TIS
但是我得到了
unhandhold异常:System.Indexoutofbound异常:索引超出了数组的界限

//我的代码是

using System;
public class n2
{

    public static void Main(String[] args)
    {

        String s1;
        Console.WriteLine("Enter the string");
        s1=Console.ReadLine();
        Console.WriteLine(s1);
        char[] charArr=s1.ToCharArray();

        for(int i=0;i<s1.Length;i++)
        {
            Console.WriteLine(charArr[i]);
        }

        Console.WriteLine(s1.Length);
        char[] n1= new char[s1.Length];
        n1[0]=charArr[0];

        for(int j=1;j<s1.Length-1;j++)
        {               
                if(charArr[j]==' ')
                {   
                for(int k=1;k<10;k++)
                    {       
                        n1[k]=charArr[++j];
                    }
                          }     
        }

        for(int i=0;i<10;i++)
        {
            Console.Write(n1[i]);
        }   

    }
}
使用系统;
公开课n2
{
公共静态void Main(字符串[]args)
{
字符串s1;
Console.WriteLine(“输入字符串”);
s1=Console.ReadLine();
控制台写入线(s1);
char[]charArr=s1.ToCharArray();

对于(int i=0;i代码中的问题在
n1[k]=charArr[++j]行;
您需要在
charArr[++j]
之前检查
if
子句中的
charArr[++j]
的值

if(j<s1.Length-1)
{
   n1[k]=charArr[j++]; //doing post increment!
}

if(j错误的直接原因是

  n1[k]=charArr[++j]; 
但是,正则表达式和Linq似乎是一种更好的方法:

  String source = "This Is Stackoverflow";

  // "TIS"
  String result = String.Join("", Regex
    .Matches(source, @"(^| )\w")
    .OfType<Match>()
    .Select(m => m.Value.Trim()));
String source=“这是Stackoverflow”;
//“TIS”
String result=String.Join(“),Regex
.Matches(来源@“(^ |)\w”)
第()类
.Select(m=>m.Value.Trim());

In second for loop变量j增加了两次。这导致了异常。我建议您学习调试。这是一项重要的技能。我想您的得票率下降是因为您没有尝试自己调试它,这会很容易解决您的问题。这项任务看起来像是某种家庭作业^^不是您最喜欢的课程,@neeraj,是吗?谢谢,它很管用…@JenishYes刚刚开始学这个,这就是为什么problem@Patric