Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 4 CS2012.

Similar presentations


Presentation on theme: "Lecture 4 CS2012."— Presentation transcript:

1 Lecture 4 CS2012

2 Strings A String consists of zero or more characters
String is a class that contains many methods Strings are more complicated than they sound!

3 Constructing Strings String newString = new String(stringLiteral);
String message = new String("Welcome to Java"); Since strings are used frequently, Java provides a shorthand initializer for creating a string: String message = "Welcome to Java"; 3

4 Variables vs Objects Consider this code: int myInt = 1; 1 is a value
myInt is a variable String s1 = "The moon is made of green cheese." "The moon is made of green cheese" is a String, an object of class String. s1 is a variable 4

5 Null A null value is one that does not exist. Variables whose data type is a class, like String, may exist without having any value: String s = null; A variable whose type is a primitive data type will be null if no value is set, but can't be set to null int x; // ok int x = null; //syntax error 5

6 Strings Are Immutable A String object is immutable; its contents cannot be changed. The following code does not change the contents of the String, it makes the variable s point to a different String in memory. String s = "Java"; s = "HTML"; 6

7 Interned Strings Since strings are immutable, if two different variables need to point to identical Strings, there is no need to save two separate Strings in memory. The JVM usually uses a unique instance for each set of string literals with the same character sequence. In other words, the following code sets up one String in memory, but two variables that point to it: String s1 = "John"; String s2 = "John"; Such an instance is said to be interned. If you set up a new String using the full new String syntax, however, the JVM will not use an interned String even if there is one with identical text. This code sets up two separate Strings with identical characters: String s1 = "John"' String s2 = new String("John"); 7

8 String Comparisons .equals(String otherString) test whether the text of this String is the same as the text of the other String 8

9 Examples s1 == s2 is false, because the == operation for Strings tests whether two Strings are the same object in memory, and we did not use the interned String s1 == s3 is true because without the new String() syntax, we used the interned String. Thus, s1 and s3 point to the same object in memory. 9

10 String Comparisons equals String s1 = new String("Welcome“);
String s2 = "welcome"; if (s1.equals(s2)){ // s1 and s2 have the same contents } if (s1 == s2) { // s1 and s2 have the same memory reference 10

11 String Comparisons, cont.
compareTo(Object object) String s1 = new String("Welcome"); String s2 = "welcome"; if (s1.compareTo(s2) > 0) { // s1 is greater than s2 } else if (s1.compareTo(s2) == 0) { // s1 and s2 have the same contents else // s1 is less than s2 11

12 public class StringDemo{
public static void main(String[] args){ String s1 = new String("Welcome"); String s2 = "welcome"; String s3 = s1; String s4 = new String("Welcome"); if (s1.equals(s2)){ System.out.println("s1 equals s2"); } else System.out.println("s1 does not equal s2"); if (s1 == s2) { System.out.println("s1 == s2"); else System.out.println("s1 != s2"); if (s1.equals(s3)){ System.out.println("s1 equals s3"); if (s1 == s3) { System.out.println("s1 == s3"); else System.out.println("s1 != s3"); if (s1.equals(s4)){ System.out.println("s1 equals s4"); else System.out.println("s1 does not equal s4"); if (s1 == s4){ System.out.println("s1 == s4"); else System.out.println("s1 != s4"); if (s1.compareTo(s2) < 0) { System.out.println("s1 < s2");

13 Escape Sequences Some characters will cause confusion in output
What will happen if we try to execute this: System.out.println(""Hi,Mom""); Others, like backspace and tab, can’t be unambiguously typed Use escape characters for these cases 13

14 Escape Sequences Description Escape Sequence Backspace \b Tab \t
Linefeed \n Carriage return \r (think of a typewriter) Backslash \\ Single Quote \' Double Quote \" 14

15 Escape Sequences } public class EscapeDemo{
public static void main(String[] args) { System.out.println("A\tB\rB\tC D\nDD\b E\\F \'Hi, Mom\' \"Hi, Mom\""); System.out.println("She said \"They tried to make me go to rehab, but I said \"No, No, No!\"\""); } 15

16 String Concatenation Appending a String or character to the end of another String is called concatenation. Three strings concatenated: String message = "Welcome " + "to " + "Java"; String s1 concatenated with character B: String s1 = "Supplement" + 'B'; // s1 becomes SupplementB To concatenate to existing String, create a new String and use concat(): String myString = "Good"; String myOtherString = myString.concat(" Morning"); 16

17 String Concatenation String s3 = s1.concat(s2); String s3 = s1 + s2;
s1 + s2 + s3 + s4 + s5 same as (((s1.concat(s2)).concat(s3)).concat(s4)).concat(s5); 17

18 String Length, Characters, and Combining Strings
18

19 Finding String Length message = "Welcome";
Finding string length using the length() method: message = "Welcome"; message.length() (returns 7) 19

20 Retrieving Individual Characters in a String
Do not use message[0] Use message.charAt(index) Index starts from 0 20

21 Strings public static void main(String[] args){
String s1 = new String("Welcome"); String s2 = " Shriners"; String s3 = s1.concat(s2); System.out.println(s3); String s4 = s1 + s2; System.out.println(s4); s1 = s1 + s2; System.out.println(s1); if(s1.startsWith("Wel")) System.out.println("\"" + s1 + "\"" + " starts with \"Wel!\""); System.out.println("Length of \"" + s1 + "\" is " + s1.length()); System.out.println("In the string \"" + s1 + "\", the character at position 4 is " + s1.charAt(4)); }

22 Extracting Substrings
22

23 Extracting Substrings
You can extract a single character from a string using the charAt method. You can also extract a substring from a string using the substring method in the String class. String s1 = "Welcome to Java"; String s2 = s1.substring(0, 11) + "HTML"; 23

24 Converting, Replacing, and Splitting Strings
24

25 Examples "Welcome".toLowerCase() returns a new string, welcome.
"Welcome".toUpperCase() returns a new string, WELCOME. " Welcome ".trim() returns a new string, Welcome. "Welcome".replace('e', 'A') returns a new string, WAlcomA. "Welcome".replaceFirst("e", "AB") returns a new string, WABlcome. "Welcome".replace("e", "AB") returns a new string, WABlcomAB. "Welcome".replace("el", "AB") returns a new string, WABlcome. 25

26 Finding a Character or a Substring in a String
26

27 Finding a Character or a Substring in a String
"Welcome to Java".indexOf('W') returns 0. "Welcome to Java".indexOf('x') returns -1. "Welcome to Java".indexOf('o', 5) returns 9. "Welcome to Java".indexOf("come") returns 3. "Welcome to Java".indexOf("Java", 5) returns 11. "Welcome to Java".indexOf("java", 5) returns -1. "Welcome to Java".lastIndexOf('a') returns 14. 27

28 public static void main(String[] args){
String theString = "The baby fell out of the window\nI thought that her head would be split\nBut good luck was with " +" us that morning\nFor she fell in a bucket of #$%*!\n\nHere we are in this fancy French restaurant\nI hate to be " +" raising a snit\nBut waiter, I ordered creamed vichysoisse\nand you brought me a bowl full of #$%*!\n\n"; System.out.println("\nOld:\n" + theString); String newString = theString.replace("#$%*!", "shaving cream\nBe nice and clean\nShave every day and you'll always look keen!\n"); System.out.println("New:\n" + newString); }

29 StringBuilder The StringBuilder class is a supplement to the String class. StringBuilder is more flexible than String. You can add, insert, or append new contents into a string buffer, whereas the value of a String object is fixed once the string is created. You will often have to parse the StringBuilder to a String when you are done constructing it. 29

30 StringBuilder Constructors
30

31 Modifying Strings in the Builder
31

32 The toString, capacity, length, setLength, and charAt Methods
32

33 Examples 33 public static void main(String[] args) {
StringBuilder stringBuilder = new StringBuilder("Welcome to "); System.out.println(stringBuilder); stringBuilder.append("Java"); stringBuilder.insert(11, "HTML and "); stringBuilder.delete(8, 11); // changes the builder to Welcome HTML and Java. stringBuilder.deleteCharAt(8); // changes the builder to Welcome TML and Java. stringBuilder.reverse(); // changes the builder to avaJ dna LMT emocleW stringBuilder.reverse(); // undoes the reverse() stringBuilder.replace(11, 15, " to"); // changes the builder to Welcome TML to Java. stringBuilder.delete(7,11); // back to Welcome to Java stringBuilder.setCharAt(0, 'w'); // sets the builder to welcome to Java. } 33

34 StringBuilder public class StringBuilderDemo{
public static void main(String[] Args){ StringBuilder sb = new StringBuilder("Bakey"); System.out.println(sb); sb.insert(4, "ry"); sb.deleteCharAt(5); // this will not do what you expect! sb.append(" " + sb.reverse()); sb.delete(sb.indexOf(" "), sb.length()); StringBuilder sb2 = new StringBuilder(sb); sb2.reverse(); sb.append(sb2); sb.insert(5," "); sb.replace(0,0,"Y"); sb.deleteCharAt(1); sb.reverse(); }

35 Appendix H Regular Expressions A regular expression (abbreviated regex) is a string that describes a pattern for matching a set of strings. Regular expression is a powerful tool for string manipulations. You can use regular expressions for matching, replacing, and splitting strings. 35

36 Matching, Replacing and Splitting by Patterns
You can match, replace, or split a string by specifying a Regex. This is an extremely useful and powerful feature. Regular expression usage is complex to beginning students. For this reason, two simple patterns are used in this section. Please refer to Supplement III.F, “Regular Expressions,” for further studies. "Java".matches("Java"); "Java".equals("Java"); "Java is fun".matches("Java.*"); "Java is cool".matches("Java.*"); 36

37 Matching, Replacing and Splitting by Patterns
The replaceAll, replaceFirst, and split methods can be used with a regular expression. For example, the following statement returns a new string that replaces $, +, or # in "a+b$#c" by the string NNN. String s = "a+b$#c".replaceAll("[$+#]", "NNN"); System.out.println(s); Here the regular expression [$+#] specifies a pattern that matches $, +, or #. So, the output is aNNNbNNNNNNc. 37

38 Matching, Replacing and Splitting by Patterns
The following statement splits the string into an array of strings delimited by some punctuation marks. String[] tokens = "Java,C?C#,C++".split("[.,:;?]"); for (int i = 0; i < tokens.length; i++) System.out.println(tokens[i]); 38

39 Matching Strings "Java".matches("Java"); "Java".equals("Java");
Appendix H Matching Strings "Java".matches("Java"); "Java".equals("Java"); "Java is fun".matches("Java.*") "Java is cool".matches("Java.*") "Java is powerful".matches("Java.*") 39

40 Regular Expression Syntax
Appendix H Regular Expression Syntax 40

41 Examples String s = "Java Java Java".replaceAll("v\\w", "wi") ;
Appendix H Examples String s = "Java Java Java".replaceAll("v\\w", "wi") ; String s = "Java Java Java".replaceFirst("v\\w", "wi") ; String[] s = "Java1HTML2Perl".split("\\d"); 41


Download ppt "Lecture 4 CS2012."

Similar presentations


Ads by Google