Getting array out of ArrayOutOfBound exception. I was writing code to get first letters of all words in a string

huangapple go评论83阅读模式
英文:

Getting array out of ArrayOutOfBound exception. I was writing code to get first letters of all words in a string

问题

// 我正在编写代码,以获取字符串中所有单词的首字母。
public class Firstword {

    static void func(String str) {
        String k = "";
        String str1 = " " + str;
        char[] ch = str1.toCharArray();
        for (int i = 0; i < ch.length - 2; i++) {
            if (i != ch.length - 1)
                while (i < ch.length && ch[i] != ' ')
                    i++;

            k = k + ch[i + 1];
        }
        System.out.print(k);
        System.out.print(ch.length);
    }

    public static void main(String[] args) {
        String str = "Hello Banner jee";

        func(str);
    }

}
英文:

//. I was writing code to get first letters of all words in a string.
public class Firstword {

static void func(String str)
{
    String k =&quot;&quot;;
   String str1=&quot; &quot;+str;
    char[] ch= str1.toCharArray();
    for(int i=0;i&lt;ch.length-2;i++)
        {
            if(i != ch.length-1)
            while(i&lt;ch.length &amp;&amp; ch[i]!=&#39; &#39;)
                i++;
            
            k=k+ch[i+1];
        }
    System.out.print(k);
    System.out.print(ch.length);
}

public static void main(String[] args)
{
    String str = &quot;Hello Banner jee&quot;;
    
    func(str);
}

}

答案1

得分: 0

Your error is here:

  k = k + ch[i+1];

You are getting out of bounds.

Because of this:

  while (i < ch.length && ch[i] != ' ')
            i++;

Something like this will work -

static void func(String str)
{
    String[] words = str.split(" ");
    for (int i = 0; i < words.length; i++) {
        System.out.println(words[i].charAt(0));
    }
}

public static void main(String[] args)
{
    String str = "Hello Banner jee";
    func(str);
}

Output -

H
B
j
英文:

Your error is here:

  k=k+ch[i+1];

You are getting out of bounds.

Because of this:

  while(i&lt;ch.length &amp;&amp; ch[i]!=&#39; &#39;)
            i++; 

Something like this will work -

static void func(String str)
{
String [] words = str.split(&quot; &quot;);
for(int i = 0; i &lt; words.length ;i++){
    System.out.println(words[i].charAt(0));
}
}

public static void main(String[] args)
{
String str = &quot;Hello Banner jee&quot;;
func(str);
}

Output -

H
B
j

huangapple
  • 本文由 发表于 2020年3月15日 16:51:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/60691158.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定