0% found this document useful (0 votes)
18 views10 pages

VXL String function_081904

Uploaded by

parnikapatel599
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views10 pages

VXL String function_081904

Uploaded by

parnikapatel599
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

CHAPTER : String Handling

Working with Strings : (User defined data type)

- Strings in Java are created by declaring object of String type class and
initializing it with a string literal.(Eg:”Java”, “Hello” etc)
- String class instances or objects can hold unchanging string (immutable
String) ie., once initialized its contents cannot be modified.
- In Java, string is basically an object that represents sequence of char
values.
For example, "hello" is a string containing a sequence of characters 'H' , 'e' ,
'l' , 'l' , and 'o' .

Creating Strings:

String str;

Or

String str=”Hello”

Or

String str=new String(“Hello”);

String class methods :


double sqrt(int)
eg : double res=Math.sqrt(25);

1 ) int length() – returns the number of letters/characters in a string variable.


Example :
String str=”Hello”; H e l l o
0 1 2 3 4
int len=str.length();
System.out.println(len);// 5
2) char charAt(int index) – returns a character from a string at specified index
Example : //Considering str=”Hello” as given above
char ch=str.charAt(1);
System.out.println(ch);// e

3) String toLowerCase() –returns given string in lowercase.


Example :
String str=”CompUTer123”;
String res=str.toLowerCase();
System.out.println(res);//computer123
System.out.println(str);//CompUTer123

4) String toUpperCase() –returns given string in uppercase


Example :
String str=”CompUTer123”;
String res=str.toUpperCase();
System.out.println(res);//COMPUTER123
System.out.println(str);//CompUTer123

5) String trim() – removes space from both ends of the given string
Example : Hi Java
String str=” Hi Java “; 0 1 2 3 4 5 6 7 8 9 10 11 12 13

// There are 2 spaces in the beginning and in between 3 spaces and at the end 3
spaces.
//the below command is to check the length before applying trim() command, so
that changes can be verified by applying trim() command
int len=str.length();
System.out.println(len);//14 – check the string with index given in pic
System.out.println(“Hello”+str+”easy”); //Hello Hi Java easy

( check the spaces )


//removes the spaces at the beginning and at the end
String res=str.trim();
System.out.println(res);//Hi Java
System.out.println(“Hello”+res+”easy”);//HelloHi Javaeasy
Note :Check the output given above , only the space at the beginning and at the
end is removed but the space in between the string remains as it is.
In the above example 3 spaces in between Hi and Java remains as it is.

len=res.length();
System.out.println(len);//9 , previously length was 14
System.out.println(“Hello”+str+”easy”); //Hello Hi Java easy
Note : Original string remains unchanged

6) int indexOf(char ch) – returns the index of the first occurrence of specified
character from a given string.
Example :String str=”Letter”; L e t t e r
0 1 2 3 4 5

int pos=str.indexOf(„e‟);
System.out.println(pos);//1
7) int lastIindexOf(char ch) – returns the index of the last occurrence of
specified character from a given string.
Example :String str=”Letter”;

int pos=str.lastIndexOf(„e‟); L e t t e r
0 1 2 3 4 5
System.out.println(pos);//4
8) String concat(String str) – Concatenate the specified string to the end of the
given string
Example :
String str1=”Computer”;
String str2=”Applications”;
String str3=str1.concat(str2);
System.out.println(str1);//Computer
System.out.println(str2);//Applications
System.out.println(str3);//ComputerApplications
OR , using + to concatenate ,
Str3=str1+str2;

9) String replace(char oldchar,char newchar) – returns a string by replaces all


occurrences of old character with the new character specified.
Example :
String str1=”Hello”;
String res=str1.replace(„l‟,‟*‟);
System.out.println(str1);//Hello
System.out.println(res);//He**o

10) String substring(int begindex) – returns a part of the string(substring) from


the specified index till the end of given string.
Example “
String str=”Examination”;
String res=str.substring(5); E xa m i n a t i o n
System.out.println(res);//nation 0 1 2 3 4 5 6 7 8 9 10

System.out.println(str);// Examination
10) String substring(int begindex,int endIndex) - returns a part of the
string(substring) from the beginning index up to the ending index specified from a
given string.
Note : Extracts up to ending index( Excluding ending index)
String str=”Examination”;
String res=str.substring(0,4); E xa m i n a t i o n
0 1 2 3 4 5 6 7 8 9 10
System.out.println(res);//Exam
System.out.println(str);// Examination Up to 4 but 4 not included

11) boolean equals(String)


- return type ie., output of equals() is boolean type.
- returns true if two strings are equal otherwise returns false.
Eg1 : String s1=”Hello”;
String s2=”HELLO”;
boolean res=s1.equals(s2);
System.out.println(res);//false because it is case sensitive ie uppercase and
lowercase letters are treated differently.
Eg2 : String s1=”Hello”;
String s2=”Hello”;
boolean res=s1.equals(s2);
System.out.println(res);//true

12) boolean equalsIgnoreCase(String)


- return type ie., output of equalsIgnoreCase() is boolean type.
- returns true if two strings are equal by ignoring cases otherwise returns false.
Eg1:
String s1=”Hello”;
String s2=”HELLO”;
boolean res=s1.equalsIgnoreCase(s2);
System.out.println(res);//true – Ignores case and checks for equality.

Eg2 : String s1=”Hello”;


String s2=”Java”;
boolean res=s1.equalsIgnoreCase(s2);
System.out.println(res);//false

13) boolean startsWith(String srch)


- return type ie., output of startsWith() is boolean type.
- returns true if a string is starting with search pattern otherwise returns
false.
Eg1 : String s1=”Hello”;
boolean res=s1.startsWith(“HE”);
System.out.println(res);//false because it is case sensitive ie
uppercase and lowercase letters are treated
differently ie He is not same as HE.
Eg2 : String s1=”Hello”;
boolean res=s1.startsWith(“He”);
System.out.println(res);//true

14) boolean endsWith(String srch)


- return type ie., output of endsWith() is boolean type.
- returns true if a string is ending with search pattern otherwise returns
false.

Eg1 : String s1=”World!”;


boolean res=s1.endsWith(“rld”);
System.out.println(res);//false because ! is missing ie., it ends with
rld!

Eg2 : String s1=” World!”;


boolean res=s1.endsWith(“rld!”);
System.out.println(res);//true

15) int compareTo(String)


 return type is integer ie., result obtained be compareTo command is of
type int.
 Compares two strings lexicographically (dictionary order). ie.,
o If s1 is bigger than s2 then it given +ve result ( >0 )
o If s1 is less than s2 then it gives –ve result ( <0)
o If s1 is equal to s2 the it gives result as 0

Eg 1: String s1=”Adit”;
String s2=”Abhi”
int res=s1.compareTo(s2);
System.out.println(res); // 2

Explanation:
First letters of both the strings are same , therefore it takes the 2nd letter & the
letters are different , then it gives difference of these letters.
S1 - d – Ascii value 100
S2 - b – Ascii value-------- 98
Difference 2 ( +ve result ie., when string1>string2 it gives >0)

Eg2 : String s1=”Adit”;


String s2=”Abhi”
int res=s2.compareTo(s1);
System.out.println(res); // -2

1st string 2nd string

Explanation:
First letters of both the strings are same , therefore it takes the 2nd letter & the
letters are different , then it gives difference of these letters.
S2 - b – Ascii value 98
S1 - d – Ascii value------- 100
Difference -2 ( -ve result ie., when string1<string2 then <0)

Eg3 : String s1=”Adit”;


String s2=”Adit”;
int res=s1.compareTo(s2);
System.out.println(res); // 0 because both the strings are equal

Eg4 : String s1=”ABHI”;


String s2=”Abhi”;
int res=s1.compareTo (s2);
System.out.println(res); // -32 because 66-98= - 32
Explanation:

S1 - B – Ascii value 66
S2 - b – Ascii value-------- 98
Difference -32 ( -ve result ie., when string1<string2 then <0))

16) int compareToIgnoreCase (String)


 return type is integer ie., result obtained be compareToIgnoreCase
command is of type int.
 Compares two strings lexicographically (dictionary order)by ignoring the
cases ie.,
o If s1 is bigger than s2 then it given +ve result ( >0 )
o If s1 is less than s2 then it gives –ve result ( <0)
o If s1 is equal to s2 the it gives result as 0
Eg4 : String s1=”ABHI”;
String s2=”Abhi”;
int res=s1.compareToIgnoreCase(s2);
System.out.println(res); // 0 because both the strings are
equal by ignoring the case.
Explanation:

S1 - B – Ascii value 66
S2 - B – Ascii value ------- 66
Difference 0 ( Zero result ie., when string1=
String2 then 0))

17) String valueOf(all types) - returns the String representation of the type of data
passed to it as an argument .

Example :
1) to convert an integer to String
int i=100;
String s1=String.valueOf(i);// converts int to String
System.out.println(s1+9); //1009 – concatenates as 100 is String type

2) To convert float to string


float num=50.75f;
String s2=String.valueOf(num);
System.out.println(s2+34); //50.7534

Objective type questions :


[ Give 2 lines gap between the questions to write the answers & will be
discussed in Online class]
I . Give java instructions for the following :
1. Store “Bangalore” in a variable place.
2. Print the number of characters in above place.
3. Input a student First name in a variable First [ Eg. Subhash”]
4. Input a student Middle name in a variable Mid[ Eg : Chandra ]
5. Input surname(Lastname) in a variable Last.[ Eg: Bose]
6. Concatenate First,Mid and Last name separated by space and store it in a variable
Stdname.
Eg :Subhash Chandra Bose
7. Extract the letters from variable Place so as to get the output as – B‟lore
8. Extract only the first and last name from the variable stdname.
9. Compare Place with “BANGALORE” and store the result in a variable boolean
res.
10. Compare the stdname with “SUBHASH” and collect the result in a variable
diff1.
11. Compare the stdname with “SUBHASH” by ignoring the case and collect the
result in a variable diff2.
12. Check whether the stdname is starting with “SA” and collect the result in a
variable result.
13. Compare place name “bangalore” by ignoring the case and collect the result in
a variable ans.
14. Check whether the stdname is ending with “SE” and collect the result in a
variable chk.
15. Convert the stdname to uppercase and print it.
17. Print index number of the first and last occurrence of the letter „s‟ and collect
the result in a variable pos1 and pos2.
18. Print the first and last letter from the string Place.
19. Replace all occurrence of the letter ‘a’in a variable Place and print it.
20. Convert the number 100.50 to its equivalent string.

Practice 25A HW questions on String Handling


1. Write a program to initialize string with a full path and filename as given below :
String str=”C:\Users\Student\Prgrams\file1.java”
Using String methods extract and output the file path, filename and extension separately
as shown. Also check whether given file is java file or not , and display Type of the file
as “ Java File “ or “Not a java file"
Output : PATH : C:\Users\Student\Prgrams\
FILE NAME : file1
EXTENSION : java
TYPE : JAVA FILE
Solution :
Program :
class PR25A_HW1
{
static void main()
{
String str="C:\\Users\\Student\\Prgrams\\file1.java";
String path,file,ext;
int p1,p2;
p1=str.lastIndexOf('\\');
path=str.substring(0,p1+1);
p2=str.indexOf('.');
file=str.substring(p1+1,p2);
ext=str.substring(p2);
System.out.println("PATH :"+path);
System.out.println("FILE :"+file);
System.out.println("EXTENSION :"+ext);
if(str.endsWith(".java"))
System.out.println("TYPE : JAVA FILE");
else
System.out.println("TYPE : NOT A JAVA FILE");
}
} Input/Output
PATH :C:\Users\Student\Prgrams\
FILE :file1
EXTENSION :.java
TYPE : JAVA FILE

2. Write a program to initialize a variable name as given below :


String name=”Subhash Chandra Bose”.
Using string methods extract first name last name and middle name as given below :

Output :
First Name : Subhash
Middle Name : Chandra
Last Name : Bose

You might also like