How to insert a string in beginning of another string in java?


Using a character array

  • Get the both strings, suppose we have a string str1 and the string to be added at begin of str1 is str2.

  • Create a character array with the sum of lengths of the two Strings as its length.

  • Starting from 0th position fill each element in the array with the characters of str2.

  • Now, from (length of str2)th position to the end of the array fill the character from the 1st array.

Example

import java.util.Scanner;
public class StringBufferExample {
   public static void main(String args[]) {
      System.out.println("Enter string1: ");
      Scanner sc= new Scanner(System.in);
      String str1 = sc.next();
      System.out.println("Enter string2: ");
      String str2 = sc.next();
      char charArray[] = new char[str1.length()+str2.length()];
      for(int i = 0; i < str2.length(); i++) {
         charArray[i]= str2.charAt(i);
      }
      for(int i = str2.length(); i < charArray.length; i++ ) {
         charArray[i] = str1.charAt(i-str2.length());
      }
      String result = new String(charArray);
      System.out.println(result);
   }
}

Output

Enter string1:
krishna
Enter string2:
kasyap
kasyapkrishna

Using a StringBuffer

Java provides StringBuffer class as a replacement of Strings in places where there is a necessity to make a lot of modifications to Strings of characters. You can modify/manipulate the contents of a StringBuffer over and over again without leaving behind a lot of new unused objects.

The append() method of this class accept a String value as a parameter and adds it to the current StringBuffer object.

The toString() method of this class returns the contents of the current StringBuffer object as a String.

Therefore, to add one string at the starting position of the other −

  • Get the both strings, suppose we have a string str1 and the string to be added at begin of str1 is str2.

  • Create an empty StringBuffer object.

  • Initially, append str2 to the above created StringBuffer object, using the append() method, Then, append str1.

  • Finally, convert the StringBuffer String using the toString() method.

Example

import java.util.Scanner;
public class StringBufferExample {
   public static void main(String args[]) {
      System.out.println("Enter string1: ");
      Scanner sc= new Scanner(System.in);
      String str1 = sc.next();
      System.out.println("Enter string2: ");
      String str2 = sc.next();
      StringBuffer sb = new StringBuffer();
      sb.append(str2);
      sb.append(str1);
      String result = sb.toString();
      System.out.println(result);
   }
}

Output

Enter string1:
krishna
Enter string2:
kasyap
kasyapkrishna
raja
Published on 10-Oct-2019 12:36:47
Advertisements