Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

1

Lecture Seventeen: Characters and Strings

Programming Fundamentals in
Java

Lecture Seventeen

Subjects:
17.1
17.2
17.3
17.4
17.5
17.6
17.7
17.8

Initializing Strings
Methods length, charAt and getChars
Comparing Strings
Methods startsWith and endsWith
Locating Characters and Substrings in Strings
Extracting Substrings from Strings
Concatenating Strings
Other String Methods

Ihab A. Mohammed
Ihab A. Mohammed

2011

Lecture Seventeen: Characters and Strings

17.1 Initializing Strings


Strings can be initialized in many different ways, for example:
Example 1:
// Program 1
public class Ex_1 {
public static void main(String[] args) {
String s1 = new String();
String s2 = new String("hello");
String s3 = new String(s2);
char[] charArray = {'g','o','o','d',' ','j','o','b'};
String s4 = new String(charArray);
String s5 = new String(charArray, 5, 3);
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s4);
System.out.println(s5);
}
}

17.2 Methods length, charAt and getChars


Length is used to return the length of a String, charAt return a character at a
specific location in a String, and getChars retrieve a set of characters from a String as
a char array.
Example 2: Write a method to accept a String and return the number of occurrences
of the character d using charAt:
public static int ex2(String str) {
int co = 0;
for(int i=0; i<str.length(); i++)
if(str.charAt(i) == 'd')
++co;
return co;
}

Example 3: Write a method to accept a String and return the number of occurrences
of the character d using getChars:
public static int ex3(String str) {
int co = 0;
char[] charAry = new char[str.length()];
str.getChars(0, str.length(), charAry, 0);
for(int i=0; i<str.length(); i++)
if(charAry[i] == 'd')
++co;
return co;
}
Ihab A. Mohammed

2011

Lecture Seventeen: Characters and Strings

Note that getChars requires 4 parameters: (the start index in the String, the number of
characters to retrieve from the String, the character array name, the start index in the
character array).

17.3 Comparing Strings


Four methods can be used to compare String: equals, equalsIgnoreCase,
compareTo, and regionMatches.
Example 4: Write a method to compare two strings using all available methods:
public static void ex4() {
String s1 = new String("hello");
String s2 = "goodbye";
String s3 = "Happy Birthday";
String s4 = "happy birthday";
if(s1.equals("hello"))
System.out.println("s1 equals \"hello\"");
else
System.out.println("s1 does not equals \"hello\"");
if(s1 == "hello")
System.out.println("s1 object == \"hello\" object");
else
System.out.println("s1 object != \"hello\" object");
if(s3.equalsIgnoreCase(s4))
System.out.println("s3 equals s4, case ignored");
else
System.out.println("s3 does not equal s4, case ignore");
System.out.println("s1
System.out.println("s2
System.out.println("s3
System.out.println("s4

compareTo
compareTo
compareTo
compareTo

s2:
s1:
s4:
s3:

"
"
"
"

+
+
+
+

s1.compaeTo(s2));
s2.compaeTo(s1));
s3.compaeTo(s4));
s4.compaeTo(s3));

if(s3.regionMatches(0, s4, 0, 5))


System.out.println("first 5 characters of s3 and s4 match");

else
System.out.println("first 5 characters of s3 and s4 do not match");

if(s3.regionMatches(true, 0, s4, 0, 5))


System.out.println("first 5 characters of s3 and s4 match with case ignored");

else
System.out.println("first 5 characters of s3 and s4 do not match");

Ihab A. Mohammed

2011

Lecture Seventeen: Characters and Strings

17.4 Methods startsWith and endsWith


Method startsWith is used to check if a string starts with a specific substring and
endsWith is used to check if a string ends with a specific substring, they return either
true or false, for example the string hello starts with the substring he starting
from location 0 and starts with the substring ll at location 2, and ends with the
substring llo.
Method startsWith and endsWith accept one argument which is the substring to
search for. Method startsWith also can take 2 arguments which are the substring and
the start index, for example to check if hello starts with the substring ll use:
String s = hello;
s.startsWith(s, 2);

to start the search from index 2 which is the third location.


Example 5: Write a method to accept an array of strings (mobile names) and return
the number of nokia mobiles:
public static int ex5(String[] mobileNames) {
int i, co = 0;
for(String mobile : mobileNames)
if(mobile.startsWith("nokia") || mobile.endsWith("nokia"))

++co;
return co;
}

17.5 Locating Characters and Substrings in Strings


To search for a specific character or substring in a specific string use the methods
indexOf and lastIndexOf which accept either one argument (the substring) or 2
arguments (the substring and the start index) and returns the index of the first
occurrence (for indexOF) or last occurrence (for lastIndexOf) of the substring if it is
found, and returns -1 if it is not found.
Example 6: Write a method to accept an array of strings (names) and return the
number of names that contains the name ahmed:
public static int ex6(String[] names) {
int i, co = 0;
for(String name : names)
if(name.indexOf("ahmed") >= 0)

++co;
return co;
}

Example 7: Write a method to accept an array of strings (names) and return the
number of names that contains the letter m starting from index 2:
Ihab A. Mohammed

2011

Lecture Seventeen: Characters and Strings


public static int ex7(String[] names) {
int i, co = 0;
for(String name : names)
if(name.indexOf('m', 2) >= 0)
++co;
return co;
}

17.6 Extracting Substrings from Strings


The substring method is used to retrieve a copy of a substring from a specific
string and as shown below:
Example 8: Write a method to accept a string and return the substring starting from
index 2 to the end:
public static String ex8(String str) {
return(str.substring(2));
}

Example 9: Write a method to accept a string and return the substring starting from
index 2 and with 4 letters:
public static String ex9(String str) {
return(str.substring(2, 6));
}

17.7 Concatenating Strings


Use method concat to concatenate two strings and as shown in the following
example:
Example 10: Write a method to declare two strings then display the concatenation of
the first with the second:
public static void ex10() {
String s1 = "happy";
String s2 = "birthday";
System.out.println(s1.concat(s2));
System.out.println("s1 after concat: " + s1);
System.out.println("s2 after concat: " + s2);
}

17.8 Other String Methods


Use method toUpperCase and toLowerCase to change the case of letters in a string.
Use method trim to remove white-space characters.
Use toCharArray to convert the string into a new character array.
Use valueOf to convert any type to a string.
Ihab A. Mohammed

2011

You might also like