16.5k views
5 votes
Write a function "doubleChar(" str) which returns a string where for every character in the original string, there are two characters.

User Dafi
by
6.0k points

1 Answer

1 vote

Answer:

//Begin class definition

public class DoubleCharTest{

//Begin the main method

public static void main(String [ ] args){

//Call the doubleChar method and pass some argument

System.out.println(doubleChar("There"));

}

//Method doubleChar

//Receives the original string as parameter

//Returns a new string where for every character in

//the original string, there are two characters

public static String doubleChar(String str){

//Initialize the new string to empty string

String newString = "";

//loop through each character in the original string

for(int i=0; i<str.length(); i++){

//At each cycle, get the character at that cycle

//and concatenate it with the new string twice

newString += str.charAt(i) + "" + str.charAt(i);

}

//End the for loop

//Return the new string

return newString;

} //End of the method

} // End of class declaration

Sample Output:

TThheerree

Step-by-step explanation:

The code above has been written in Java and it contains comments explaining each line of the code. Kindly go through the comments. The actual lines of executable codes have been written in bold-face to differentiate them from comments.

A sample output has also been given.

Snapshots of the program and sample output have also been attached.

Write a function "doubleChar(" str) which returns a string where for every-example-1
Write a function "doubleChar(" str) which returns a string where for every-example-2
User Max Kanter
by
7.0k points