String Class and Printing
String Class and Printing
22
7 4. char str.charAt(int index): It is used to get the character at the given index
8 number.
9 Example:
10 String name = ‘Shreyash’;
11 System.out.println(name.charAt (0));
12 O/P: S
13 5. int indexOf(String s): It is used to get the starting index of a given particular
14 character or of the given String.
15 Example:
16 String name = “Shreyash”;
17 System.out.println(name.indexOf(‘h’));
18 O/P: 1
19 6. int lastIndexOf(Strign s): It is used to get the ending index of a given
20 particular character or of the given String.
21 Example:
22 String name = “Shreyash”;
23 System.out.println(name.lastIndexOf(‘h’));
24 O/P: 7
25
6 51.String Methods #3
7 1. boolean equals(String s): It is used to compare two strings.
8 It compare only the literals(value).
9 *Unlike == compares references.
10 2. boolean equalsIgnoreCase(String s): It is used to equate strings without
11 considering case of the Strings.
12 Example:
13 str1.equalsIgnoreCase(str2);
14
6 6. String valueOf(int i): It is used converting any value of any datatype into
7 String. This is a static method.
8
9 Example:
10 public class Three
11 {
12 public static void main(String[] args)
13 {
14 String str2="java";
15 String str1 = new String("java");
16 String str3="python";
17 String str4="Python";
18 System.out.println(str2.equals(str3));
19 System.out.println(str2.equalsIgnoreCase(str3));
20 System.out.println(str4.compareTo(str3));
21 System.out.println(str2.valueOf(21));
22
23 // reference
24 System.out.println(str1 == str2);
25 System.out.println(str2.equals(str1));
26
27 System.out.println(str1.valueOf(21).getClass());
28
29
30 }
31 }
32
33
34
44 1. W.A.P
1 a. Remove Special characters from a string.
2 b. Remove extra spaces from string.
3 c. Find number of words in a String
4 2. String replaceAll(String s): It is used to replace string with a sub-string of
5 a give string.
6 3. Split(String s): It is used to split the string according to the string and return
7 the array.
8
9 *Notes:
10 1. We can’t use meta characters in normal String functions except matches().
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
1
10