Strings in Java 1. strings in java are handled by two classes String &

Slides:



Advertisements
Similar presentations
Java
Advertisements

Purpose : To convert this string to a new character array. Return Type : char[ ] Parameters : none Declaration : public char[ ] toCharArray() Returns.
String Pemrograman Berbasis Obyek Oleh Tita Karlita.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 9 Strings.
Chapter 7 Strings F To process strings using the String class, the StringBuffer class, and the StringTokenizer class. F To use the String class to process.
1 Working with String Duo Wei CS110A_ Empty Strings An empty string has no characters; its length is 0. Not to be confused with an uninitialized.
1 Strings and Text I/O. 2 Motivations Often you encounter the problems that involve string processing and file input and output. Suppose you need to write.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 8 Strings.
Java Programming Strings Chapter 7.
Strings An extension of types A class that encompasses a character array and provides many useful behaviors Chapter 9 Strings are IMMUTABLE.
Chapter 10 Review. Write a method that returns true is s1 and s2 end with the same character; otherwise return false. Sample Answer: public boolean lastChar(String.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 9 Strings and Text I/O.
Java Strings in 10 minutes
©2004 Brooks/Cole Chapter 7 Strings and Characters.
String class  Construct a string  String str = new String(“welcome”);  Char[] charr = {‘G’, ‘o’, ‘o’, ‘d’};  String mes = new String(charr);  A full.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 9 Characters and Strings (sections ,
J.43 ARRAYS  A Java array is an Object that holds an ordered collection of elements.  Components of an array can be primitive types or may reference.
CSM-Java Programming-I Spring,2005 String Handling Lesson - 6.
Fundamental Programming Structures in Java: Strings.
28-Jun-15 String and StringBuilder Part I: String.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 9 Characters and Strings (sections ,
Lesson 3 – Regular Expressions Sandeepa Harshanganie Kannangara MBCS | B.Sc. (special) in MIT.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Lecture 14 March 23, Exam Results Class Average was 69.4 –Median was 72.5 (which means there were some very low grades) Questions 31, 32, and 33.
The java.lang Package chapter 8 Java Certification Study Group February 2, 1998 Seth Ladd.
Chapter 7 Strings  Use the String class to process fixed strings.  Use the StringBuffer class to process flexible strings.  Use the StringTokenizer.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
Chapter 7: Characters, Strings, and the StringBuilder.
CHAPTER 9 Text Processing and More about Wrapper Classes Copyright © 2016 Pearson Education, Inc., Hoboken NJ.
1 Textual Data Many computer applications manipulate textual data word processors web browsers online dictionaries.
String Handling StringBuffer class character class StringTokenizer class.
Jaeki Song JAVA Lecture 07 String. Jaeki Song JAVA Outline String class String comparisons String conversions StringBuffer class StringTokenizer class.
1 The String Class F Constructing a String: F Obtaining String length and Retrieving Individual Characters in a string F String Concatenation (concat)
String Definition A String is a set of characters that behaves as a single unit. The characters in a String include upper-case and lower-case letters,
Vladimir Misic: Characters and Strings1Tuesday, 9:39 AM Characters and Strings.
G51PR1 Introduction to Programming I University of Nottingham Unit 8 : Strings.
1 Java Strings Dr. Randy M. Kaplan. 2 Strings – 1 Characters are a fundamental data type in Java It is common to assemble characters into units called.
CSI 3125, Preliminaries, page 1 String. CSI 3125, Preliminaries, page 2 String Class Java provides the String class to create and manipulate strings.
Chapter 3A Strings. Using Predefined Classes & Methods in a Program To use a method you must know: 1.Name of class containing method (Math) 2.Name of.
Java String 1. String String is basically an object that represents sequence of char values. An array of characters works same as java string. For example:
String handling. when you create a String object, you are creating a string that cannot be changed. That is, once a String object has been created, you.
Strings Can view as array of chartacters –Implemented as a class with its own methods Simplest operation on strings is catenating two strings String x.
17-Feb-16 String and StringBuilder Part I: String.
Computer Programming 2 Lab (1) I.Fatimah Alzahrani.
Chapter 8 String Manipulation
The Methods and What You Need to Know for the AP Exam
The String class is defined in the java.lang package
Introduction to programming in java
String and StringBuffer classes
Strings, Characters and Regular Expressions
Strings, StringBuilder, and Character
String class.
EKT 472: Object Oriented Programming
String and String Buffers
String Handling in JAVA
Primitive Types Vs. Reference Types, Strings, Enumerations
Modern Programming Tools And Techniques-I Lecture 11: String Handling
Chapter 7: Strings and Characters
Object Oriented Programming
MSIS 655 Advanced Business Applications Programming
Part a: Fundamentals & Class String
Java – String Handling.
CS2011 Introduction to Programming I Strings
Strings in Java.
Chapter 7 Strings Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. Use the String class to process fixed.
Switch, Strings, and ArrayLists in Java
In Java, strings are objects that belong to class java.lang.String .
Presentation transcript:

Strings in Java 1. strings in java are handled by two classes String & StringBuffer 2. String -- Immutable class, StringBuffer - Mutable class 3. Constructors : String() 2. String(char chars[]) 3. String(char chars[],int start, int numChars) 4. String(String x) 5. String(byte bytes[]) 6. String(byte bytes[],int start, int numChars) << Creates an Empty String >> << Creates a String frorm char Array>> << Creates a String frorm char Array from start to start+numChars -1 >> << Creates a String frorm another String >> << Creates a String frorm byte Array>> << Creates a String frorm byte Array from start to start+numChars -1 >>

String Examples String s1 = “Object” OR String s1 = new String(“Object”); String s1 = new String(); 3. char[ ] names ={ ‘O’,’B’, ‘J’,’E’, ‘C’,’T’, ‘ ‘,‘O’,’R’, ‘I’,’E’, ‘N’,’T’, ‘E’,’D’}; String s1 = new String(names); String s2 = new String(names,2,4); String s3 = new String(names,6,10); String s4 = new String(names,6,-4); 4. byte[ ] values = { 10,45,67,34,68,66 }; String s1 = new String(values); String s2 = new String(values, 2,3); String s3 = new String(values,2,6); 5. String s1 = “Object”; String s2 = new String(s1); << Empty String Created>> << s1 will be “OBJECT ORIENTED”>> << s2 will be “JECT”>> << StringIndexOutOfBoundsException>> << s1 will be “ -C"DB”>> << s2 will be “ C"D”>> << StringIndexOutOfBoundsException>> << Creating String from another String>>

String s1 = new String(“OOP”); String Examples cont.. String s1 =“OOP”; String s2 =“OOP”; String s3 =“OOP”; String s1 = new String(“OOP”); String: s1 OOP s2 s3

String Length int length() << Returns the length of String>> Usage : <string>.length(); Examples : S.O.P(“Object”.length()); s1.length(); name.length(); 6

String Concatenation Adding Strings together <<Concatenation>> ‘+’ operator can be used to concatenate two strings String concat(String other) method can also be used Examples : 1. String s1 = “Hello”+”How are You”+20+20; 2. String s2 = “Object” String s3 = “Programming” String s4 = s2 + s3 OR String s4 = s2.concat(s3); 3. System.out.println(“xyz”.concat(“oop”)); 4. String s1 = 20+20+“Hello”+”How are You”; // s1 will be “HelloHowareYou2020” // s1 will be “40HelloHowareYou”

Extracting a Single Character from a String char charAt(int where) charAt() method extracts a character from a string at a given index <<where>> parameter should be within range (0 to stringlength-1). Otherwise StringIndexOutOfBoundsException will be thrown Examples : char ch = “xyz”.charAt(1); // ch will be ‘y’ char ch = “xyz”.charAt(3); //StringIndexOutOfBoundsException

Extracting More than one character getChars() To Extract more than one character we can use getChars() method Syntax: void getChars (int sourceStart, int sourceEnd, char target[ ], int targetStart) Start index in Invoking String End index in Invoking String char Array where characters from string are to be stored Start index in char Array from where the characters are to be stored characters will be extracted from sourceStart to sourceEnd-1 Extracted Characters will be stored in target[] char array from index targetStart Every index either in invoking or target string should be within specified limits

D:\java\bin>java StringExamples j e c t t o getChars() Example 1 class StringExamples { public static void main(String args[]) String s1="object oriented"; char[] name = new char[10]; s1.getChars(2,6,name,0); for(int i=0;i<name.length;i++) System.out.print(name[i]+" "); System.out.println(" "); char[] name1 = new char[10]; s1.getChars(5,8,name1,3); System.out.print(name1[i]+" "); } D:\java\bin>java StringExamples j e c t t o

getChars() Example 2 s1.getChars(6,2,name,0); class StringExamples { public static void main(String args[]) String s1="object oriented"; char[] name = new char[10]; s1.getChars(6,2,name,0); for(int i=0;i<name.length;i++) System.out.print(name[i]+" "); System.out.println(" "); char[] name1 = new char[10]; s1.getChars(8,5,name1,3); System.out.print(name1[i]+" "); } D:\java\bin>java StringExamples Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String in ex out of range: -4 at java.lang.String.getChars(String.java:724) at StringExamples.main(StringExamples.java:8)

getChars() Example 3 s1.getChars(0,13,name,0); class StringExamples { public static void main(String args[]) String s1="object oriented"; char[] name = new char[10]; s1.getChars(0,13,name,0); for(int i=0;i<name.length;i++) System.out.print(name[i]+" "); System.out.println(" "); char[] name1 = new char[10]; s1.getChars(0,5,name1,3); System.out.print(name1[i]+" "); } D:\java\bin>java StringExamples Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException at java.lang.System.arraycopy(Native Method) at java.lang.String.getChars(String.java:726) at StringExamples.main(StringExamples.java:8)

String to byte Arrays byte[ ] byte[] getBytes[] Useful when exporting a String values to 8-bit ASCII code. class StringExamples { public static void main(String args[]) String s1="object oriented"; byte[] values = s1.getBytes(); for(int i=0;i<values.length;i++) System.out.print(values[i]+" "); } D:\java\bin>java StringExamples 111 98 106 101 99 116 32 111 114 105 101 110 116 101 100

String to character Arrays char[ ] char[ ] toCharArray[ ] Coverts a string to an character array class StringExamples { public static void main(String args[]) String s1="object oriented"; char[ ] values = s1.toCharArray(); for(int i=0;i<values.length;i++) System.out.print(values[i]+" "); } D:\java\bin>java StringExamples o b j e c t o r i e n t e d

String Comparisons boolean equals(Object str) boolean equalsIgnoreCase(String str) Examples : (i) “xyz”.equals(“abc”); << false>> (ii) “xyz”.equalsIgnoreCase(“XYZ”) << true> (iii) s1.equals(s2) << returns if s1 and s2 are equal>> (iv) s1.equalsIgnoreCase(s2) << returns if s1 and s2 are equal by ignoring case>>

Comparing Regions For matching Used for comparing selected regions within strings. Two Methods can be used: 1. boolean regionMatches(int startIndex, String str2,int str2StartIndex, int numChars) Start index within invoking String Start index within str2 String No of characters to be matched String with whom invoking string will be matched

Comparing Regions For matching 2. boolean regionMatches(boolean ignorecase, int startIndex, String str2,int str2StartIndex, int numChars) << Used When matching is to be done by ignoring case>> True means case is ignored False means case is not ignored. Same as previous method

Region matches Examples String s1 = “ It is time to start preparation for the incoming exams”; String s2 = “ Indian team will start preparation for the match”; String s3 = “ INDIAN TEAM WILL START PREPARATION FOR THE MATCH”; S1.regionMatches(4,s2,6,10); false S1.regionMatches(14,s2,17,17); true S1.regionMatches(14,s3,17,17); false S1.regionMatches(true,14,s2,17,17); true

boolean startsWith(String str) boolean endsWith(String str) Can be used to check whether a string starts/ends with a string str or not Examples : “object”.startsWith(“obj”) << true>> “Indians love cricket”.endsWith(“cricket”); << true>> Second Form of startsWith allows to specify the starting point: boolean startsWith(String str, int startIndex); “Indians love cricket”.startsWith(“love”,8); << true>> endsWith has only one form and is not available in boolean endsWith(String str, int startIndex);

equals Vs == String s1 = new String(“OOP”); How Many Objects are created? TWO if (s1 == s2) S.O.P(“Hello”); else S.O.P(Hi”); What will be output? Hi = = checks whether two string references are pointing to same string object or not. if (s1.equals(s2)) S.O.P(“Hello”); else S.O.P(Hi”); What will be output? Hello equals( ) checks whether contents of two strings are pointing two same object or not.

equlas Vs == cont.. String s1 = new String(“OOP”); String s2 = s1 How Many Objects are created? ONE if (s1 == s2) S.O.P(“Hello”); else S.O.P(Hi”); What will be output? Hello if (s1.equals(s2)) S.O.P(“Hello”); else S.O.P(Hi”); What will be output? Hello

int compareTo(String str) int compareToIgnoreCase(String str) Used for String comparisons. Returns one of the three possible values: <0 invoking string is less than str >0 invoking string is greater than str =0 if both strings are equal Used for ordering/sorting strings

String Comparison Examples String s1 = "OOP"; String s2 = "OOP"; String s3 = "java"; if( s1 == s2) System.out.println("Hello"); else System.out.println("Hi"); System.out.println(s1.compareTo(s3)); System.out.println(s3.compareTo(s1)); How Many Objects are created here?. ONE Hello -27 27

Searching Strings

indexOf() lastIndexOf() Used searching first/last occurences of a character / substring Return the index of character or substring if found otherwise -1 These two methods are overloaded in several different ways int indexOf(int ch) / int lastIndexOf(int ch) int indexOf(String str) / int lastIndexOf(String str) int indexOf(int ch, int startIndex) / int lastIndexOf(int ch, int startIndex) int indexOf(String str,startIndex) / int lastIndexOf(String str, int startIndex)

Example 7 66 33 49 49 33 System.out.println(s1.indexOf('t')); String s1 = "Now is the time for all good men to come forward to aid their country"; System.out.println(s1.indexOf('t')); System.out.println(s1.lastIndexOf('t')); System.out.println(s1.indexOf("to")); System.out.println(s1.lastIndexOf("to")); System.out.println(s1.indexOf("to",35)); System.out.println(s1.lastIndexOf("to",35)); 7 66 33 49 49 33

Extracting a SubString From String String substring(int startIndex) Returns a substring from invoking string starting form startIndex up to last of the invoking string “I Love India”.substring(7); startIndex <= invoking string length – 1. String substring(int startIndex, int endIndex) Returns a substring from invoking string starting form startIndex up to endIndex-1 endIndex > startIndex and both should be within permitted range. “I Love India”.substring(2,6);

all good men to come forward to aid their country Substring Example String s1 = "Now is the time for all good men to come forward to aid their country"; System.out.println(s1.substring(20)); System.out.println(s1.substring(20,40)); System.out.println("object oriented".substring(6)); System.out.println("object oriented".substring(5,10)); Index 20 to end all good men to come forward to aid their country Index 20 to 39 all good men to come Index 6 to end oriented Index 5 to 9 t ori

Complete the Constructor class Course { private String courseNo; private int compCode; private String courseName; Course(String courseString) // courseString has first 10 places for courseNo // Next 4 places for comp code // Next 30 places for courseName courseNo = courseString.substring(0,10); compcode = Integer.parseInt(courseString.substring(10,14)); courseName = courseString.substring(14); }

Character Replacement in a String String replace(char original, char replacement) Replaces all occurences of one character with replacement character in the invoking string “Hello”.replace(‘l’,’w’); << l with w>> String trim() Removes any leading and trailing whitespaces “ Hello World “.trim(); << returns Hello World>> 3. Useful for processing user commands

Changing Case of Characters Within a String String toLowerCase() String toUpperCase() Examples : S.O.P(“object”.toUpperCase()); S.O.P(“OBJECT”.toLowerCase());

String toString() Converts any object reference to String form This method is by default supplied by Object class. toString() method in Object class returns the hascode value of Object in String form Any class can override this method with following syntax: public String toString() { …………….. return <anyString> }

class A { int a,b; A(int a,int b) this.a = a; this.b = b; } This class A does not supply any toString() method. So it will be called from Object class class test100 { public static void main(String args[]) A a1 = new A(10,8); System.out.println(a1); } Name of class HashCode of Object OUTPUT A@10b62c9

public static void main(String args[]) A a1 = new A(10,8); class A { int a,b; A(int a,int b) this.a = a; this.b = b; } public String toString() return "a="+a+"b="+b; This class A supplies a toString() method. So it will be called from class A itself class test100 { public static void main(String args[]) A a1 = new A(10,8); System.out.println(a1); } a=10b=8 Change this statement to return “Hello Java”; Recompile and ReExcecute the Program

Home Exercise void sort(String[] arr, boolean isAscending) void sort(String[] arr, int fromIndex, int toIndex, boolean isAscending) boolean isRefelexiveMirror(String other) “RAM” and “MAR” are reflexive mirrors “XYZ” and “ZYX” are reflexive mirrors “object” and “tebojc” are reflexive mirrors static boolean isRefelexiveMirror(String first, String second) boolean contains(String other) << whether a string contains other or not. static boolean contains(String f1, String f2)