Chapter 3: String
-
Upload
nasim-alvarez -
Category
Documents
-
view
39 -
download
2
description
Transcript of Chapter 3: String
Chapter 3: String
String and String Method
Chapter Objectives
2
String Class Commonly Used String Methods Parsing Numeric Strings
The class String
3
Contains operations to manipulate strings. String:
Sequence of zero or more characters. Enclosed in double quotation marks. Is processed as a single unit . Null or empty strings have no characters. “ “ Every character has a relative position , the first
character is in position 0 .
Java Programming: From Problem Analysis to Program Design, Second Edition 4
The class String
Java system automatically makes the class String available (i.e no need to import this class )
Example :
Consider the following declaration :
String sentence ;
sentence = “programming with java”;
The class String
5
Length of the string is the number of characters in it. When determining the length of a string, blanks
count. Example :
“ “ has length = 0 “abc” has length = 3, position of a = 0, b= 1, c= 2 “a boy” has length = 5
Strings and the Operator +
6
Operator + can be used to concatenate two strings, or a string and a numeric value or character.
ExampleString str;int num1, num2;num1 = 12;num2 = 26;str = "The sum = " + num1 + num2;
After this statement executes, the string assigned to str is:"The sum = 1226";
Strings and the Operator +
7
Consider the following statement:str = "The sum = " + (num1 + num2);
In this statement, because of the parentheses, you first evaluate num1 + num2.
Because num1 and num2 are both int variables, num1 + num2 = 12 + 26 = 38. After this statement executes, the string assigned to str is:
"The sum = 38";
Some Commonly Used String Methods
8
Suppose that
String sentence = "Programming with Java";. Then each character in sentence and its
position is as follows:
charAt (index):
9
method header how to use it
char charAt (int index)
char ch=sentence.charAt(3) ;System.out.println (sentence.charAt(4+2));
Returns the character at the position specified by
index
note :index should be >= 0 and <length
indexOf (ch):
10
method header how to use it
int indexOf (char ch) int i=sentence.indexOf('J');char ch ='a';System.out.println (sentence.indexOf(ch));System.out.println (sentence.indexOf('p'));
Returns the index of the first occurrence of the character specified by ch; If the character specified by ch does not appear in the string, it returns –1
indexOf (ch,pos):
11
method header how to use it
int indexOf (char ch,int pos)
char ch ='a';System.out.println (sentence.indexOf(ch,10));System.out.println (sentence.indexOf('m',9));
Returns the index of the first occurrence of the character specified by ch; The parameter pos specifies where to begin the search; If the character specified by ch does not appear in the string, it returns –1
indexOf (str):
12
method header how to use it
int indexOf (String str) System.out.println (sentence.indexOf("with"));System.out.println (sentence.indexOf("ing"));System.out.println (sentence.indexOf("the"));
Returns the index of the first occurrence of the string specified by str; If the string specified by str does not appear in the string, it returns –1
indexOf (str,pos):
13
method header how to use it
int indexOf (String str,int pos) int i=sentence.indexOf("a", 10) ;int i=sentence.indexOf("Pr", 10) ;
Returns the ??Returns the index of the first occurrence of the String specified by str; The parameter pos specifies where to begin the search; If the string specified by str does not appear in the string, it returns -1
concat(str)
14
method header how to use it
String concat(String str) Stringn Str=sentence.concat(" is fun.");
Returns the string that is this string concatenated with str
Programming with Java is fun. Stringn Str=sentence + "is fun.";
length()
15
method header how to use it
int length() int len=sentence.length();
Returns the length of the string
21
replace (ToBeReplaced,
ReplacedWith )
16
method header how to use it
String replace(char chR,char chRW )
String nStr=sentence.replace('a', '*') ;
Returns the string in which every occurrence of charToBeReplaced is replaced with charReplacedWith
Progr*mming with J*v*
substring (beginIndex,endIndex)
17
method header how to use it
String substring (int beginIndex, int endIndex);
String subStr=sentence.substring(5,11) ;
Returns the string which is a substring of this
string beginning at beginIndex until endIndex
– 1
amming
note :1. if we did not specify the endIndex, substring of this string beginning at beginIndex until the end of the string.2. beginIndex<endIndex
toLowerCase()
18
method header how to use it
String toLowerCase() String lowStr=sentence.toLowerCase() ;
Returns the string that is the same as this string,
except that all uppercase letters of this string are
replaced with their equivalent lowercase letters
programming with java
toUpperCase()
19
method header how to use it
String toUpperCase() String uppStr=sentence.toUpperCase() ;
Returns the string that is the same as this string,
except that all lowercase letters of this string are
replaced with their equivalent uppercase letters
PROGRAMMING WITH JAVA
equals(str)
20
method header how to use it
boolean equals(String str)
boolean b=sentence.equals ("programming with java") ;
Returns true if this string is same as str
False
compareTo(str)
21
method header how to use it
int compareTo(String str)
int i=sentence.compareTo ("programming with java") ;
Compares two strings character by characterReturns a negative value if this string is less than str Returns 0 if this string is same as strReturns a positive value if this string is greater than str
Java Programming: From Problem Analysis to Program Design, Second Edition
Examples on string methods
22
String s1 , s2 , s3 ;
s1 = “abcdefeg” ;
System.out.println( s1.length() ); // 8
System.out.println(s1.charAt(3)); //d
System.out.println(s1.indexOf(‘e’)); //4
System.out.println(s1.indexOf(“cd”)); //2
System.out.println(s1.toUpperCase()); //ABCDEFEG
Java Programming: From Problem Analysis to Program Design, Second Edition
Examples on string methods
23
System.out.println(s1.substring(1 , 4)); //bcdSystem.out.println(s1 + “xyz”); // abcdefegxyzSystem.out.println( s1.replace(‘d’ ,’D’)); // abcDefegSystem.out.println(s1.charAt(4) ); // eSystem.out.println(s1.indexOf(‘b’)); // 1System.out.println(s1.indexOf(‘e’,5)); // 6
Java Programming: From Problem Analysis to Program Design, Second Edition
Parsing Numeric Strings
24
Integer, Float, and Double are classes designed to convert a numeric string into a number.
These classes are called wrapper classes. parseInt is a method of the class Integer, which
converts a numeric integer string into a value of the type int.
parseFloat is a method of the class Float and is used to convert a numeric decimal string into an equivalent value of the type float.
parseDouble is a method of the class Double, which is used to convert a numeric decimal string into an equivalent value of the type double.
Java Programming: From Problem Analysis to Program Design, Second Edition
Parsing Numeric Strings
25
A string consisting of only integers or decimal numbers is called a numeric string.
To convert a string consisting of an integer to a value of the type int, we use the following expression:
Integer.parseInt(strExpression)• Example:
int i=Integer.parseInt("6723"); --> 6723int j=Integer.parseInt("-823");--> -823
Java Programming: From Problem Analysis to Program Design, Second Edition
Parsing Numeric Strings
26
To convert a string consisting of a decimal number to a value of the type float, we use the following expression:
Float.parseFloat(strExpression)• Example:
float f1=Float.parseFloat("34.56"); -> 34.56float f2=Float.parseFloat("-542.97"); -> -542.97
To convert a string consisting of a decimal number to a value of the type double, we use the following expression:
Double.parseDouble(strExpression)• Example:
double y=Double.parseDouble("345.78");--> 345.78double z=Double.parseDouble("-782.873");--> -
782.873
What is the value of each variable
27
String sentence;
sentence="Now is the time for the birthday party.";
int index = sentence.indexOf("birthday");
String str1 = sentence.substring(index, index + 14); int len =sentence.length() ;