Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert string in beginning of another string

Tags:

java

string

How to insert a string enclosed with double quotes in the beginning of the StringBuilder and String?

Eg:

StringBuilder _sb = new StringBuilder("Sam"); 

I need to insert the string "Hello" to the beginning of "Sam" and O/p is "Hello Sam".

String _s = "Jam"; 

I need to insert the string "Hello" to the beginning of "Jam" and O/p is "Hello Jam".

How to achieve this?

like image 698
Gopi Avatar asked Sep 25 '09 06:09

Gopi


People also ask

How do you add a string to the beginning of a string?

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.

How do you add a string at the beginning of a string Python?

In python, to append a string in python we will use the ” + ” operator and it will append the variable to the existing string.

How do you add a character to a string beginning in Java?

Example: One can add character at the start of String using the '+' operator.


1 Answers

The first case is done using the insert() method:

_sb.insert(0, "Hello "); 

The latter case can be done using the overloaded + operator on Strings. This uses a StringBuilder behind the scenes:

String s2 = "Hello " + _s; 
like image 103
unwind Avatar answered Sep 24 '22 15:09

unwind