Write a program to create a new string repeating every character twice of a given string


This program takes a string and returns a new string with each character repeated twice. Here's how it works:

  • First, the repeat method takes a string str as its input.
  • Then, it initializes a new string new_str to the empty string.
  • The method then loops through each character of the input string using a for loop with a loop variable i.
  • In each iteration of the loop, the method adds two copies of the current character to the new_str string using the substring method. The substring method is used to extract a single character from the input string by specifying the starting and ending indices of the substring.
  • Finally, the method returns the new_str string, which contains each character of the input string repeated twice.

In the main method, an instance of the Repeating_Char class is created, and the repeat method is called with the input string "Java". The resulting string, with each character repeated twice, is then printed to the console.

Source Code

public class Repeating_Char
{
	public String repeat(String str) 
	{
	  int l = str.length();
	  String new_str = "";
	  for (int i = 0; i < l; i++) 
	  {
		new_str += str.substring(i,i+1) + str.substring(i, i+1);
	  }
	  return new_str;
	}
	public static void main (String[] args)
	{
		Repeating_Char m= new Repeating_Char();
		String str =  "Java";
		System.out.println("Given string : "+str);
		System.out.println("Repeating Every Character in String : "+m.repeat(str));
	}
}

Output

Given string : Java
Repeating Every Character in String : JJaavvaa

Example Programs