-8

Below is my code I'm expecting the output as "afbgchde" and not "abcdefgh" but ending up with out of index error, Hope there is a better way to get this..Please help..!!

String str1 = "abcde";
//char[] a = str1.toCharArray();
//System.out.println(a);
String str2 = "fgh";
char[] b = str2.toCharArray();
//System.out.println(b);
int i,j=0;
try
    {
        for(i=0;i<str1.length();i++)
        {
          char c = str1.charAt(i);
          System.out.print(c);
          if(j==i)
          { 
            char d = str2.charAt(j);
            System.out.print(d);
            j++;
          }
        }
    }
catch(Exception e)
{
    System.out.println(e);
}
GhostCat
  • 137,827
  • 25
  • 176
  • 248
Ramraj Sekar
  • 9
  • 1
  • 1
  • 4
  • 2
    Where is the error, and what have you done to think about why you're getting it? – Jon Skeet Mar 21 '17 at 08:59
  • @JonSkeet I understood that the error is due to index value of str2 is causing the error but not getting how to handle it.. – Ramraj Sekar Mar 21 '17 at 09:38
  • 1
    Well think about *why* you're asking for a value that's out of range, and what you want to do instead. Hint: if you were asked to merge "abcdefghijklmnopqrstuvwxyz" and "12" would you keep going after you'd got to "c"? – Jon Skeet Mar 21 '17 at 11:04

4 Answers4

4

Simple:

 char d = str2.charAt(j);
 System.out.print(d);
 j++;

You are accessing chars in your second string; but you never bother to check if j is still < str2.length().

Meaning: your for-loop for i contains that check; and prevents going beyond the length of str ... but then you forget to do that on your other string! So your merge only works when str and str2 happen to have the same size.

So a solution would more look like:

 StringBuilder builder = new StringBuilder();
 int j = 0;
 for (int i=0; i < str.length(); i++) {
   builder.append(str.charAt(i));
   if (j < str2.length()) {
     builder.append(str2.charAt(j));  
     j++;
   }
 }
 // if str2 has more chars than str
 if (j < str2.length()) {
   // append ALL chars starting from index j
   builder.append(str2.substring(j));
 }
 String merged = builder.toString();
GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • Your btw is wrong, if you look at what he wants to do: he doesn't want to get `abcdefgh`, but `afbgchde`. So he doesn't want to simply concat them, but to do another operation (shown by his example) – Thomas Böhm Mar 21 '17 at 09:05
  • Thanks, overlooked that part. – GhostCat Mar 21 '17 at 09:07
  • @GhostCat Thank you, When length is equal code works perfect else getting error...It will be heplful if you could give some more details as I'm just started learning java – Ramraj Sekar Mar 21 '17 at 09:41
  • I updated my example (didnt compile/run it; so be aware of subtle typos or so). Hope that helps. – GhostCat Mar 21 '17 at 10:43
3

Complete Code for your combiner.

public class StringCombiner {
public static void main(String[] args){
    System.out.println(combine("Hello", "World"));
    System.out.println(combine("He", "World"));
    System.out.println(combine("Hello", "Wo"));
}

    public static String combine(String str1, String str2){
        StringBuilder output = new StringBuilder();
        int i =0;
        for(; i< str1.length(); ++i){
            output.append(str1.charAt(i));
            if(i < str2.length()){
                output.append(str2.charAt(i));
            }
        }
        if(i < str2.length()){
            for(; i<str2.length(); ++i){
                output.append(str2.charAt(i));
            }
        }
        return output.toString();
    }
    }

Output:

HWeolrllod
HWeorld
HWeollo

Hope this helps.

Sampath
  • 599
  • 5
  • 12
0

Okay. Lets try this

String str1 = "abcde";
String str2 = "fgh";
int bigLength = str1.length()>str2.length()?str1.length():str2.length();

for(int i = 0; i<bigLength; i++){
if(i<str1.length())
   System.out.print(str1.charAt(i))
if(i<str2.length())
   System.out.print(str2.charAt(i))
}

Hope this will work for you.

Ananda G
  • 2,389
  • 23
  • 39
0

just use StringBuilder class man

if you want to change a value of a String object

String class is an object that is unchangeable or can't be change when it is initialized

StringBuilder class is the best solution for any String that you want to have a change while the application is running

e.g. add a String or change value of a String or even shorten a String

that is the power of StringBuilder class

`

0xDEADBEEF
  • 590
  • 1
  • 5
  • 16