How to add a char to a string in Java
In this topic, we will learn how to add a char to the beginning, middle and end of a string in Java.
for insert, a char at the beginning and end of the string the simplest way is using string.
Add a character to a string in the beginning
for insert, in the beginning, we can just use additional operation.
Example:
char ch='A'; String str="pple"; str= ch+str; // str will change to "Apple"
For insert a char at the end of a string also we can use additional operation.
Example:
char ch='e'; String str="Appl"; str=str + ch; // str will change to "Apple"
Need help in Java assignment? Then visit Java Assignment Help.
Program of insert char at the beginning and end of a string in Java
import java.util.*;
public class Codespeedy {
public static void main(String[] args) {
char ch='D'; //declare a char
String str="laptop"; // declare a string
str = str + ch; // add char at the end of string
System.out.println(str); // print the result
str = ch + str; // add char at the beginning
System.out.println(str); // print the result
}
}output:
laptopD DlaptopD
Add a char (in any position) to a string by using StringBuffer in Java
By using StringBuffer we can insert char at the beginning, middle and end of a string.
For insert at the end of a StringBuffer, we can use this method:
str.append(ch);
For insert at the middle, end, and beginning we can insert method and specify the location of inserting.
Example:
StringBuffer str = new StringBuffer("java Programing");
str.insert(0,'A'); // insert 'A' at the beginning "Ajava programing"
str.insert(6,'R'); // insert at the 6th position "Ajava Aprograming"
str.insert(str.length()-1,'G'); // insert at the end by using lenght method to find last index.Program of StringBuffer fo insert char:
import java.util.*;
public class Codespeedy {
public static void main(String[] args) {
char ch='A'; //declare a char
StringBuffer str= new StringBuffer("system"); // declare a StringBuffer
str.append(ch); // add char at the end of stringbuffer
System.out.println(str); // print the result
str.insert(0,'R'); // add char R at the beginning
System.out.println(str); // print the result
str.insert(1,'-'); // add char - at position 1
System.out.println(str); // print the result
}
}Output:
systemA RsystemA R-systemA
Leave a Reply