L- 9 String Manipulation
String - - - - - - -> Sequence of characters.
In Java, sequence of group of characters are enclosed within double
quotes.
For example : “Computer” - - - > valid string constant
‘ C ‘ - - -> valid character constant
String = “Computer”
Character = ‘A’
Java implements strings as objects of class type String.
String class→ part of→ Java.lang package
If you want to store string constant “computer”
String s=”computer”;
String s = C o m p u t e r
position/ index = 0 1 2 3 4 5 6 7
● String Constructors
A string is a class in java .You can create a string by creating an
object.
String constructor - - - - -> Initialisation of string
To create an empty string - - - > you can create a default constructor.
String s= new String();
Or
String s;
s= new String;
To create a String, that is initialized with a group of characters.
-------> Parameterised constructor
String s = new String(“abcdef”);
● String Length
Use to find the number of characters in a given string
String s=”computers”; “INDIA”.length() = 5
int len=s.length(); “abc9”.length() =4
Sop(len); =9
String s=”COMPUTER APPLICATIONS”;
int len=s.length();
Sop(len); =21
● Concatenation
→Joining of 2 strings
→ + operator
There are two ways to concatenate strings in Java:
1. By + (String concatenation) operator
2. By concat() method
1) String Concatenation by + (String concatenation) operator
class TestStringConcatenation1{
public static void main(String args[]){
String s="Sachin"+" Tendulkar";
System.out.println(s);//Sachin Tendulkar
} }
class TestStringConcatenation2{
public static void main(String args[]){
String s=50+30+"Sachin"+40+40;
System.out.println(s);//80Sachin4040
} }
2) String Concatenation by concat() method
class TestStringConcatenation3{
public static void main(String args[]){
String s1="Sachin ";
String s2="Tendulkar";
String s3=s1.concat(s2);
System.out.println(s3);//Sachin Tendulkar
}
}
● The ValueOf() method
—> Converts all data types to String.
int i=456;
float f=17.34f;
double d=45.23d;
String is=String.valueOf(i); is --------> “456”
String fs=String.valueOf(f); fs---------> “17.34”
String ds=String.valueOf(d); ds--------->”45.23”
● Character Data Type
→ used to represent a single character.
→ Character literal is always enclosed within a single quote.
Ex: char ‘A’;
Characters Unicode
A to Z 65 to 90
a to z 97 to 122
0 to 9 48 to 57
char x=’A’;
int y=x;
Sop(y); → 65
class Checkdemo
{
static void test(char x)
{
if(x>='A' && x<='Z')
System.out.println("uppercase character");
else if(x>='a' && x<='z')
System.out.println("lowercase character");
}
}
● Extraction of a character from a string
→ to extract a character from a string we can use the charAt()
method.
→ position or index.
index 0 1 2 3 4 567
String s1=”COMPUTER”;
char c;
c=s1.charAt(1); —> O
public class Characters
{
static void characterWise(String sent)
{
int len;
len=sent.length();
for(int i=0;i<len;i++)
{
System.out.println(sent.charAt(i));
}
}
}
● Extraction of Substring
→part of string →substring—> substring() method
Two ways of extracting string
1. String substring(int startIndex)
Example : String s1=”COMPUTER”,s2;
s2=s1.substring(3); → will store PUTER into s2
2. String substring(int startIndex ,int endIndex)
Example: String s1=”COMPUTER”,s2;
s2=s1.substring(2,5); → will store MPU into s2
● Replacing the string
→ used to replace one character with another character.
Character
String replace(char original, char replacement)
Ex: String s1=”BABA”,s2;
s2=s1.replace(‘B’,’T;);
—> s2=TATA
String
String replace( String original , String replacement)
Ex:String s=”he went to movie and he also went to market”;
String r;
r=s.replace(“he”,”she”);
→She went to movie and She also went to market
● Equalisation of Strings( equals() method)
→ compare characters in a string and check whether two strings are
equal or not.
class String
{
static void check()
{
String s1=”COMPUTER”, s2=”COMPUTER”;
if(s1.equals(s2))
System.out.println(“Equal”);
else
System.out.println(“ Not Equal”);
}
}
The Equals() Verses ==
→Equals() compare characters in a string and check whether two
strings are equal or not.
→ The == operator compares two object references to see whether
they refer to the same instance or not.
Class StringDemo
{
Static void test()
{
String s1=”Hello”;
String s2=new string(s1);
String s3=s2;
System.out.println(s1.equals(s2)); →true
System.out.println(s1==s2); →false
System.out.println(s1.equals(s3)); —>true
System.out.println(s1==s3); —>true
}
}
Changing the case of characters within a string
→The .toUpperCase() method is used to convert all characters in a
string to capital letters.
public class StringUpperExample{
public static void main(String args[]){
String s1="hello string";
String s1upper=s1.toUpperCase();
System.out.println(s1upper); }}
→ HELLO STRING
→The .toLowerCase() method is used to convert all characters in a
string to small letters.
public class StringLowerExample{
public static void main(String args[]){
String s1="JAVATPOINT HELLO stRIng";
String s1lower=s1.toLowerCase();
System.out.println(s1lower);
}}
output→ javatpoint hello string
The StartsWith() and endsWith() methods
→The startsWith() method checks whether a string starts with the
specified character(s)
String myStr = "Hello";
System.out.println(myStr.startsWith("Hel")); // true
System.out.println(myStr.startsWith("llo")); // false
System.out.println(myStr.startsWith("o")); // false
→The endsWith() method checks whether a string ends with the
specified character(s).
String myStr = "Hello";
System.out.println(myStr.endsWith("Hel")); // false
System.out.println(myStr.endsWith("llo")); // true
System.out.println(myStr.endsWith("o")); // true
Searching Strings
IndexOf() and lastIndexOf() are used to search for a substring or
character.
IndexOf() - searches for the first occurrence of a character or
substring .
public class Test {
public static void main(String args[]) {
String str = new String("hi welcome to Tutorialspoint");
int index = str.indexOf('w');
System.out.println("Index of the letter w :: "+index);
}
}
output-Index of the letter w :: 3
lastIndexOf() - searches for the last occurrence of a character or
substring.
public class Main {
public static void main(String[] args) {
String myStr = "Hello planet earth, you are a great planet.";
System.out.println(myStr.lastIndexOf("planet"));
}
}
Output- 36
Comparison of strings ( compareTo())
String myStr1 = "Hello";
String myStr2 = "Hello";
System.out.println(myStr1.compareTo(myStr2));
// Returns 0 because they are equal
System.out.println(“abc”.compareTo(“abde”));
c=99 d=100 = 99-100= -1
System.out.println(“AB”.compareTo(“ABCD”));
No index position so it will display -2
“AB”.length()-”ABCD”.length() = 2-4= -2
“abcd”.compareTo(“abCD”)
c=99 C=67 = 99-67=32
The trim() Function
The trim() method removes whitespace from both ends of a string.
public class Main {
public static void main(String[] args) {
String myStr = " Hello World! ";
System.out.println(myStr);
System.out.println(myStr.trim());
}
}
Hello World!
Hello World!
import java.util;
public class StringDemo {
public static void main(String[] args) {
String str = " Tutorials Point ";
System.out.println("The length of the string before trimming is: "
+ str.length());
System.out.println("The string without trimming is: " + str);
String t = str.trim();
System.out.println("The length of the string after trimming is: " +
t.length());
System.out.println("The string with trimming is:" + t);
}
}
Output
The length of the string before trimming is: 25
The string without trimming is: Tutorials Point
The length of the string after trimming is: 15
The string with trimming is:Tutorials Point
Section A
Answer as directed
9. Write statements to show finding the length of a character array
and char[] differs from finding the length of a String object str.
a. For finding length of character array char[] we use, a.length
Ex: char[] a={ ‘a’,’b’};
r=a.length; //char.length
Output: 2
b. For finding length of string object str, we use, str.length();
Ex:String str=”My” ;
int k=str.length(); // str.length()
Output:2
14. Give the output of the following statements:
String x[]={“SAMSUMG’,”NOKIA”,”SONY”,”MICROMAX”,
”BLACKBERRY”};
0 1 2 3 4
{“SAMSUMG’,”NOKIA”,”SONY”,”MICROMAX”,”BLACKBERR
Y”};
i. System.out.println(x[1]); = NOKIA
ii. System.out.println(x[3].length()); = 8
15. Write the output for the following:
String s=”Today is Test”;
System.out.println(s.indexOf(‘T”));
01234 67 9101112
” Today5 is 8 Test”; → (s.indexOf(‘T”)); = 0
System.out.println(s.substring(0,7)+’’ “+”Holiday”);
0-7
Today i Holiday
21. What will the following code output?
String s=”malayalam”;
0 1 2 3 4 56 7 8
malayalam
System.out.println(s.indexOf(‘m’)); = 0
System.out.println(s.lastindexOf(‘m’));= 8
22. What will the following code output?
String n=”Computer knowledge”;
0 1 2 3 4 5 6 7 9 10 11 12 13 14 15 16 17
Computer 8 k n o w l e d g e
String m=”Computer Applications”:
0 1 2 3 4 5 6 7 9 10 11 12 13 14 15 16 17 18 19 20
Computer 8 A p p l i c a t i o n s
System.out.println(n.substring(0,8).concat(m.substring(9)));
Computer Applications
System.out.println(n.endsWith(‘e’)); = true