lecture 6 (strings in java)

Upload: deepak-dewani

Post on 30-Oct-2015

25 views

Category:

Documents


0 download

TRANSCRIPT

  • 1. strings in java are handled by two classes String & StringBuffer

    2. String -- Immutable class, StringBuffer - Mutable class

    3. Constructors :Strings in Java

    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)> > > > > >

  • String ExamplesString 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);>>>>>>

  • String Examples cont..String s1 =OOP;String s2 =OOP; String s3 =OOP;String:OOPs1String s1 = new String(OOP);s2s3

  • String Lengthint length() >Usage : .length();Examples : S.O.P(Object.length()); s1.length(); name.length();6

  • String ConcatenationAdding Strings together + operator can be used to concatenate two stringsString concat(String other) method can also be usedExamples : 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 Stringchar charAt(int where)charAt() method extracts a character from a string at a given index parameter should be within range (0 to stringlength-1). Otherwise StringIndexOutOfBoundsException will be thrownExamples : char ch = xyz.charAt(1); // ch will be y char ch = xyz.charAt(3); //StringIndexOutOfBoundsException

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

  • getChars() Example 1class 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

  • getChars() Example 2class 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

  • getChars() Example 3class 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

  • 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;ijava StringExamples111 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 arrayclass StringExamples{public static void main(String args[]){String s1="object oriented";char[ ] values = s1.toCharArray();for(int i=0;ijava StringExampleso b j e c t o r i e n t e d

  • String Comparisonsboolean equals(Object str)boolean equalsIgnoreCase(String str)Examples : (i) xyz.equals(abc); > (ii) xyz.equalsIgnoreCase(XYZ) (iii) s1.equals(s2) > (iv) s1.equalsIgnoreCase(s2) >

  • 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 String with whom invoking string will be matchedStart index within str2 String No of characters to be matched

  • Comparing Regions For matching 2. boolean regionMatches(boolean ignorecase, int startIndex, String str2,int str2StartIndex, int numChars)>True means case is ignoredFalse means case is not ignored. Same as previous method

  • Region matches ExamplesString 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);S1.regionMatches(14,s2,17,17);S1.regionMatches(14,s3,17,17);S1.regionMatches(true,14,s2,17,17);falsetruefalsetrue

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

  • equals Vs ==String s1 = new String(OOP);String s2 = new String(OOP);How Many Objects are created?TWOif (s1 == s2) S.O.P(Hello);elseS.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);elseS.O.P(Hi);What will be output?Helloequals( ) checks whether contents of two strings are pointing two same object or not.

  • equlas Vs == cont..String s1 = new String(OOP);String s2 = s1How Many Objects are created?ONEif (s1 == s2) S.O.P(Hello);elseS.O.P(Hi);What will be output?Helloif (s1.equals(s2)) S.O.P(Hello);elseS.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 greater than str =0 if both strings are equalUsed for ordering/sorting strings

  • String Comparison ExamplesString s1 = "OOP";String s2 = "OOP";String s3 = "java";

    if( s1 == s2)System.out.println("Hello");elseSystem.out.println("Hi");

    System.out.println(s1.compareTo(s3));System.out.println(s3.compareTo(s1));Hello-2727How Many Objects are created here?.ONE

  • Searching Strings

  • indexOf()lastIndexOf()Used searching first/last occurences of a character / substringReturn the index of character or substring if found otherwise -1These two methods are overloaded in several different waysint 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)

  • ExampleString 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));76633494933

  • Extracting a SubString From StringString substring(int startIndex)Returns a substring from invoking string starting form startIndex up to last of the invoking stringI Love India.substring(7); startIndex startIndex and both should be within permitted range.I Love India.substring(2,6);

  • Substring ExampleString 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));all good men to come forward to aid their countryall good men to come orientedt ori

  • Complete the Constructorclass 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 StringString replace(char original, char replacement)Replaces all occurences of one character with replacement character in the invoking stringHello.replace(l,w); >

    String trim()Removes any leading and trailing whitespaces Hello World .trim(); >3. Useful for processing user commands

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

  • String toString()Converts any object reference to String formThis method is by default supplied by Object class.toString() method in Object class returns the hascode value of Object in String formAny class can override this method with following syntax:public String toString() { .. return }

  • 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 classclass test100{public static void main(String args[]){A a1 = new A(10,8);System.out.println(a1);}}OUTPUTA@10b62c9

  • 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 itselfclass test100{public static void main(String args[]){A a1 = new A(10,8);System.out.println(a1);}}a=10b=8Change this statement to return Hello Java; Recompile and ReExcecute the Program

  • Home Exercisevoid sort(String[] arr, boolean isAscending)void sort(String[] arr, int fromIndex, int toIndex, boolean isAscending)boolean isRefelexiveMirror(String other)RAM and MAR are reflexive mirrorsXYZ and ZYX are reflexive mirrorsobject and tebojc are reflexive mirrorsstatic boolean isRefelexiveMirror(String first, String second)boolean contains(String other)