36.0k views
2 votes
Given the strings s1 and s2 that are of the same length, create a new string consisting of the first character of s1 followed by the first character of s2, followed by the second character of s1, followed by the second character of s2, and so on (in other words the new string should consist of alternating characters of s1 and s2). For example, if s1 contained "hello" and s2 contained "world", then the new string should contain "hweolrllod". Associate the new string with the variable s3.

User Scable
by
4.1k points

1 Answer

6 votes

Answer:

// class definition

class Main

{

// main function of class

public static void main (String[] args) throws java.lang.Exception

{

try{

// string variable

String s1="hello";

String s2="world";

// empty string

String s3="";

// find length of string

int len=s1.length();

for(int i=0;i<len;i++)

{

// append character of string s1

s3=s3+s1.charAt(i);

// append character of string s2

s3=s3+s2.charAt(i);

}

// print new string

System.out.println("New string is:"+s3);

}catch(Exception ex){

return;}

}

}

Step-by-step explanation:

Declare and initialize string variables "s1=hello" and "s2=world".Create an empty string "s3".Append alternate characters of both strings to string "s3". String variable s3 will have the new string.

Output:

New string is:hweolrllod

User Tnknepp
by
4.5k points