Professional Documents
Culture Documents
Alnahrain Progarming Luctuer 17
Alnahrain Progarming Luctuer 17
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
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
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).
compareTo
compareTo
compareTo
compareTo
s2:
s1:
s4:
s3:
"
"
"
"
+
+
+
+
s1.compaeTo(s2));
s2.compaeTo(s1));
s3.compaeTo(s4));
s4.compaeTo(s3));
else
System.out.println("first 5 characters of s3 and s4 do not match");
else
System.out.println("first 5 characters of s3 and s4 do not match");
Ihab A. Mohammed
2011
++co;
return co;
}
++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
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));
}
2011