String klasė http://www.fatih.edu.tr/~moktay/2009/spring/ceng104/The.String.Class.ppt.

Slides:



Advertisements
Similar presentations
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 9 Strings.
Advertisements

Strings in Java 1. strings in java are handled by two classes String &
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.
Ch 8. Characters and Strings Timothy Budd 2 Characters and Literals Strings Char in C++ is normally an 8-bit quantity, whereas in Java it is a 16-bit.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
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.
©2004 Brooks/Cole Chapter 7 Strings and Characters.
Chapter 9 Characters and Strings. Topics Character primitives Character Wrapper class More String Methods String Comparison String Buffer String Tokenizer.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 9 Characters and Strings (sections ,
CSM-Java Programming-I Spring,2005 String Handling Lesson - 6.
23-Jun-15 Strings, Etc. Part I: String s. 2 About Strings There is a special syntax for constructing strings: "Hello" Strings, unlike most other objects,
Fundamental Programming Structures in Java: Strings.
Strings, Etc. Part I: Strings. About Strings There is a special syntax for constructing strings: "Hello" Strings, unlike most other objects, have a defined.
28-Jun-15 String and StringBuilder Part I: String.
The String Class. Objectives: Learn about literal strings Learn about String constructors Learn about commonly used methods Understand immutability of.
©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.
Class T{ public static int id; public static int num = 5; public int n; public boolean c; public static void setNumberOfBicycles(int val) { num=val; //
Java Methods A & AB Chapter 10 - Strings. Ch 10 Goals Understand Strings indepth Learn strategies to deal with the immutability of Strings Learn how to.
String Class. Objectives and Goals Identify 2 types of Strings: Literal & Symbolic. Learn about String constructors and commonly used methods Learn several.
String Manipulation Chapter 15 This chapter explains the String facilities. You have already seen some of the main methods of the String class.
Strings Carol Yarbrough AP Computer Science Instructor Alabama School of Fine Arts.
Java Overview. Comments in a Java Program Comments can be single line comments like C++ Example: //This is a Java Comment Comments can be spread over.
Chapter 7: Characters, Strings, and the StringBuilder.
1 Textual Data Many computer applications manipulate textual data word processors web browsers online dictionaries.
Strings JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight.
Strings Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and.
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,
String String Builder. System.String string is the alias for System.String A string is an object of class string in the System namespace representing.
G51PR1 Introduction to Programming I University of Nottingham Unit 8 : Strings.
Strings and ArrayLists April 23, 2012 ASFA AP CS.
Strings and Related Classes String and character processing Class java.lang.String Class java.lang.StringBuffer Class java.lang.Character Class java.util.StringTokenizer.
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:
17-Feb-16 String and StringBuilder Part I: String.
Vaizdinė užduotis. Kuriose iš šių valstybių galima pamatyti tokius gyvenamuosius namus? Jemene Tanzanijoje Mongolijoje Indonezijoje A B C D 1.
Strings A string is a sequence of characters that is treated as a single value. Strings are objects. We have been using strings all along. For example,
"Chapter 9" Strings Java Methods Maria Litvin Gary Litvin
The Methods and What You Need to Know for the AP Exam
The String Class.
Strings, Characters and Regular Expressions
Strings, Characters and Regular Expressions
Strings, StringBuilder, and Character
EKT 472: Object Oriented Programming
String and String Buffers
String String Builder.
String Class.
Strings Chapter 6.
Primitive Types Vs. Reference Types, Strings, Enumerations
String Objects & its Methods
A few bits of information
Modern Programming Tools And Techniques-I Lecture 11: String Handling
String and StringBuilder
Object Oriented Programming (OOP) LAB # 8
Object Oriented Programming
MSIS 655 Advanced Business Applications Programming
String and StringBuilder
String and StringBuilder
Things to Remember.
Java – String Handling.
16 Strings.
String and StringBuilder
String methods 26-Apr-19.
Visual Programming COMP-315
In Java, strings are objects that belong to class java.lang.String .
Unit-2 Objects and Classes
Presentation transcript:

String klasė http://www.fatih.edu.tr/~moktay/2009/spring/ceng104/The.String.Class.ppt

Turinys: Tiesioginės eilutės Eilučių konstruktoriai Dažniausiai naudojami String klasės metodai Eilučių nekeičiamumas Skaičiaus vertimas eilute

Apie String klasę String tipo klasės objektas apibrėžia eilutės simbolių seką String klasė yra java.lang pakete, kuris nereikalauja jo importavimo sakinio. Kaip ir kitos klasės, String turi aibę konstruktorių ir metodų. Skirtingai nuo kitų klasių, String objektams galima taikyti dvi operacijas: + ir +=, kurios apjungia eilutes.

Tiesioginės (literal) eilutės tai bevardžiai String objektai. apibrėžiamos parašant tekstą kabutėse: “Tai tiesioginė eilutė” nekviečia konstruktoriaus. gali būti priskirtos String tipo kintamiesiems. gali būti perduotos konstruktorių ir eilučių parametrais. Turi aibę naudingų String klasės metodų.

Tiesioginių eilučių pavyzdžiai //priskiriame tiesioginę eilutę kintamajam String vardas = “Robertas”; //kviečiame tiesioginės eilutės metodą char pirmojiRaidė = “Robert”.charAt(0); //kviečiame String kintamojo metodą char pirmasisSimbolis = vardas.charAt(0);

String nekintamumas Kartą sukurta, eilutė negali būti pakeista Objektai pasižymintys tokia savybe vadinami nekintamais (immutable). Nekintami objektai patogūs tuo, kad visos nuorodos į juos yra saugios, nes nėra pavojaus, kad objekto turinys pakito ir skirtingos nuorodos žymi skirtingo turinio objektą.

Nekintamų objektų privalumai Naudoja mažiau atminties String zodis1 = "Java"; String zodis2 = zodis1; String zodis1 = “Java"; String zodis2 = new String(zodis1); zodis 1 “Java" zodis 1 “Java" zodis 2 “Java" zodis 2 Netaupiai eikvojama atmintis OK

Nekintamumo trūkumai Neefektyvu, kai jums reikia naujos panašaus turinio eilutės. String zodis = “java"; char ch = Character.toUpperCase(zodis.charAt (0)); zodis = ch + zodis.substring (1); zodis “java" “Java"

Tuščios eilutės Tuščia eilutė neturi nei vieno simbolio; jos ilgis lygus 0. Tuščia eilutė skiriasi nuo neinicijuotos:. String word1 = ""; String word2 = new String(); Empty strings private String errorMsg; errorMsg yra null

Konstruktorius su tuščiu parametrų sąrašu () Toks konstruktorius sukuria tuščią eilutę. Naudojamas retai. Dažniau tokiu atveju naudojama tuščia tiesioginė eilutė. Tuščia eilutė dažnai yra analogas pradinės nulinės reikšmės kaupiant sumą. String tuščia = new String(); String tuščia = “”;//tarp kabučių nieko nėra

Eilutės kopijavimas panaudojant konstruktorių Egzistuojančios eilutės kopija gaunama kreipiantis į konstruktorių perduodant parametru kopijuojamos eilutės objektą. Taip pat retai naudojama. Skiriasi nuo priskyrimo operatoriaus. zodis “Java" String zodis = new String(“Java”); String zodis2 = new String(zodis); “Java" zodis2 Priskiriant: abu kintamieji tampa nuorodomis į tą pačią eilutę. zodis String zodis = “Java”; String zodis2 = zodis; “Java" zodis2

Kiti konstruktoriai Dauguma naudoja masyvą, kad sukurti eilutę. char[] raides = {‘J’, ‘a’, ‘v’, ‘a’}; String zodis = new String(raides);//”Java” byte[] baitai = {(byte)0x4a, (byte)0x61, (byte)0x76, (byte)0x61}; String zodis = new String(baitai);//”Java”

Metodai — length, charAt int length(); char charAt(i); Grąžina kiek eilutėje yra simbolių Grąžina simbolį esantį i-ojoje pozicijoje. Simboliai, kaip ir masyvų atveju, numeruojami pradedant nuo nulinės pozicijos. Grąžina: ”Žodis".length(); ”Žodis".charAt (2); 5 ’d'

substring metodas String subs = zodis.substring (i, k); television Grąžina naują eilutę kopijuojant nurodytų simbolių seką. String subs = zodis.substring (i, k); qrąžina eilutę sudarytą iš simbolių esančių nuo i iki k-1 pozicijos String subs = zodis.substring (i); grąžina eilutę pradedant nuo i-osios pozicijos iki galo. television i k television i Grąžina: ”television".substring (2,5); “immutable".substring (2); “zodis".substring (9); “lev" “mutable" "" (tuščia eilutė)

Sujungimo metodai String result = zodis1 + zodis2; String zodis1 = “ap”, zodis2 = “gal”; zodis3 = “voti”; int num = 2; String result = zodis1 + zodis2; //apjungiami zodis1 ir zodis2 “apgal“ String result = zodis1.concat (zodis2); //tas pats kaip zodis1 + zodis2 “apgal“ result += zodis3; //prijungia zodis3 prie result “apgalvoti” result += num; //konvertuoja num į eilutę //ir prijungia ją prie result “apgalvoti2”

indexOf metodas ᆪ j ᆲ ᆲ ᆲ String vardas =“Prezidentas Valdas Adamkus"; 0 2 6 12 21 ᆪ j ᆲ ᆲ ᆲ String vardas =“Prezidentas Valdas Adamkus"; vardas.indexOf (‘P'); 0 vardas.indexOf (‘e'); 2 vardas.indexOf (“Vadas"); 1 vardas.indexOf (‘e', 3); 6 vardas.indexOf (“Jonas"); -1 vardas.lastIndexOf (‘a'); 21 Grąžina: (ieško pradedant 3-ia pozicija) String has four overloaded versions of indexOf and four versions of lastIndexOf. lastIndexOf(ch, fromPos) starts looking at fromPos and goes backward towards the beginning of the string. (nerasta)

Eilučių sutapimo (equals) metodas boolean b = zodis1.equals(zodis2); grąžina true jei zodis1 sutampa su zodis2 boolean b = zodis1.equalsIgnoreCase(zodis2); grąžina true jei zodis1 sutampa su zodis2 ignoruojant didžiųjų/mažųjų raidžių skirtumą b = “Raiders”.equals(“Raiders”);//true b = “Raiders”.equals(“raiders”);//false b = “Raiders”.equalsIgnoreCase(“raiders”);//true You cannot use relational operators for comparing the contents of strings. zodis1.compareTo(zodis2) returns an int. Basically if zodis1 is “smaller” than zodis2, the result is negative, and if word1 is “larger” the result is positive. compareTo returns 0 whenever equals returns true. Here is how Java docs describe compareTo: Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argument string. The result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal; compareTo returns 0 exactly when the equals(Object) method would return true. This is the definition of lexicographic ordering. If two strings are different, then either they have different characters at some index that is a valid index for both strings, or their lengths are different, or both. If they have different characters at one or more index positions, let k be the smallest such index; then the string whose character at position k has the smaller value, as determined by using the < operator, lexicographically precedes the other string. In this case, compareTo returns the difference of the two character values at position k in the two string — that is, the value: this.charAt(k)-anotherString.charAt(k) If there is no index position at which they differ, then the shorter string lexicographically precedes the longer string. In this case, compareTo returns the difference of the lengths of the strings — that is, the value: this.length()-anotherString.length() if(team.equalsIgnoreCase(“raiders”)) System.out.println(“Go You “ + team);

Eilučių palyginimo (comapreTo) metodas int diff = zodis1.compareTo(zodis2); grąžina “skirtumą” zodis1 - zodis2 int diff = zodis1.compareToIgnoreCase(zodis2); grąžina “skirtumą” zodis1 - zodis2, ignoruojant didžiųjų/mažųjų skirtumą Dažnai konkreti “skirtumo” zodis1 - zodis2 reikšmė nenaudojama, o tik skirtumo ženklas. Jei „skirtumas“ neigiamas, zodis1 eina prieš zodis2, lygus nuliui - zodis1 ir zodis2 sutampa, teigiamas - zodis1 eina po zodis2. Pvz. You cannot use relational operators for comparing the contents of strings. word1.compareTo(word2) returns an int. Basically if word1 is “smaller” than word2, the result is negative, and if word1 is “larger” the result is positive. compareTo returns 0 whenever equals returns true. Here is how Java docs describe compareTo: Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argument string. The result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal; compareTo returns 0 exactly when the equals(Object) method would return true. This is the definition of lexicographic ordering. If two strings are different, then either they have different characters at some index that is a valid index for both strings, or their lengths are different, or both. If they have different characters at one or more index positions, let k be the smallest such index; then the string whose character at position k has the smaller value, as determined by using the < operator, lexicographically precedes the other string. In this case, compareTo returns the difference of the two character values at position k in the two string — that is, the value: this.charAt(k)-anotherString.charAt(k) If there is no index position at which they differ, then the shorter string lexicographically precedes the longer string. In this case, compareTo returns the difference of the lengths of the strings — that is, the value: this.length()-anotherString.length() if (zodis1.compareTo(zodis2) > 0){ //zodis1 eina po zodis2… }

Palyginimo pavyzdžiai //neigiami skirtumai diff = “apple”.compareTo(“berry”);//a prieš b diff = “Zebra”.compareTo(“apple”);//Z prieš a diff = “dig”.compareTo(“dug”);//i prieš u diff = “dig”.compareTo(“digs”);//dig trumpesnis //nulinis skirtumas diff = “apple”.compareTo(“apple”);//sutampa diff = “di”.compareToIgnoreCase(“DI”);//sutampa //teigiami skirtumai diff = “berry”.compareTo(“apple”);//b po a diff = “apple”.compareTo(“Apple”);//a po A diff = “BIT”.compareTo(“BIG”);//T po G diff = “huge”.compareTo(“hug”);//huge ilgesnis

trim metodas String zodis2 = zodis1.trim (); grąžina naują eilutę sudarytą iš zodis1 atmetus jos pradžioje ir gale esančius tarpus. Viduriniai tarpai neatmetami. String zodis1 = “ Sveikas, Jonai ! “; String zodis2 = zodis1.trim(); //zodis2 yra “Sveikas, Jonai !” – be tarpų galuose //zodis1 lieka “ Sveikas, Jonai ! “ – su tarpais Note that these methods do not change the string word1 but create and return a new string. trim() only removes whitespace at the ends of the string, not in the middle.

replace metodas String zodis2 = zodis1.replace(senaChar, nujaChar); grąžina naują eilutę, kurioje zodis1 eilutėje visi senaChar simboliai pakeisti naujaChar simboliu String zodis1 = “mama“; String zodis2 = zodis1.replace(‘m’, ‘p’); //zodis2 yra “papa”, o zodis1 lieka “mama“ Note that these methods do not change the string word1 but create and return a new string. trim() only removes whitespace at the ends of the string, not in the middle.

Didžiųjų/mažųjų raidžių keitimas String zodis2 = zodis1.toUpperCase(); String zodis3 = zodis1.toLowerCase(); grąžina naują eilutę pakeičiant zodis1 mažąsias (didžiąsias) raides didžiosiomis (mažosiomis) String zodis1 = “SveiKas“; String zodis2 = zodis1.toUpperCase();//”SVEIKAS” String zodis3 = zodis1.toLowerCase();//”sveikas” //zodis1 lieka “SveiKas“ Note that these methods do not change the string word1 but create and return a new string. trim() only removes whitespace at the ends of the string, not in the middle.

zodis1 lieka nepakeistu. Pakeitimai Pvz, kad pakeisti zodis1 jo didžiosiomis raidėmis, reikia parašyti. Tipinė klaida: zodis1 = zodis1.toUpperCase(); zodis1 lieka nepakeistu. zodis1.toUpperCase(); word1.toUpperCase(); doesn’t do anything. The correct statement is: word1 = word1.toUpperCase(); The variable word1 is changed to refer to the new string returned by word1.toUpperCase(); the old string is disposed of.

Skaičių vertimas tekstu Yra trys būdai tai padaryti: 1. String s = "" + skaicius; 2. String s = Integer.toString (i); String s = Double.toString (d); 3. String s = String.valueOf (num); Integer ir Double yra int ir double pirminių klasių analogai, kurie skaičius išreiškia objektais. Jie turi aibę naudingų statinių metodų, vienu kurių čia ir pasinaudojome. s = “” + 123;//”123” s = Integer.toString(123);//”123” s = Double.toString(3.14); //”3.14” You can also convert a char to a string by using String s = "" + ch; or String s = ch + ""; By convention, a static method valueOf in a class converts something (its arguments) into an object of this class. For example: public class Fraction { public static Fraction valueOf(double x) {...} should take a double and return a corresponding Fraction. Here String.valueOf(x) returns a string. s = String.valueOf(123);//”1 23”

Klausimai pakartojimui: Kokiam paketui priklauso String klasė? Kuo skiriasi String klasės objektai nuo kitų klasių? “Kaip vadinamas tekstas tarp kabučių ?” Kokia reikšmė bus grąžinta: “Laba diena”.length()? Kokie objektai vadinami “immutable” ? What makes the String class unusual? + and += operators and literal strings How can you include a double quote character into a literal string? \" Is "length".length() allowed syntax? If so, what is the returned value? Yes, it is valid and returns 6. Define immutable objects. Objects that cannot be changed by calling their methods (nor by directly manipulating their fields). Does immutability of strings make Java more efficient or less efficient? It depends. It may be more efficient if the code involves making many copies of strings. It is less efficient if the code involves changing characters in strings or assembling strings from separate items (chars or numbers). Actually the latter situation is more common. You should then use the StringBuffer class rather than String.

Klausimai pakartojimui: Kokie nekintanmų String tipo objektų Javoje privalumai? Kokie nekintanmų String tipo objektų Javoje trūkumai? Kaip apibrėžti tuščią eilutę? “Jonas” + “ “ + “Petras” vadinama ____ ? How do you declare an empty string? String s = ""; Why are String constructors not used very often? Because you can simply assign a literal string to a variable, so there is no need to make copies of strings. If the value of String city is "Boston", what is returned by city.charAt(2)? By city.substring(2,4)? 's' and "st", respectively. How come String doesn’t have a setCharAt method? To keep it immutable. StringBuffer has setCharAt(ch,pos). Is s1 += s2 the same as s1 = s1 + s2 for strings? Yes.

Klausimai pakartojimui: String miestas = "Vilnius“; Ką grąžins miestas.charAt (2)? mietas.substring(2, 4)? miestas.lastIndexOf(‘i’)? miestas.indexOf(3)? Ką atlieka trim metodas? What do the indexOf methods do? Name a few overloaded versions. Find a character or a substring in a string. indexOf(char), indexOf(String), indexOf(char, int fromPos), indexOf(String, int fromPos) What is more efficient for strings: == and other relational operators or equals and compareTo methods? This is not a matter of efficiency: you must use equals and compareTo to compare the contents of strings; == compares references, which are equal only if they refer to exactly the same string. What does the trim method do? It returns a new string which contains this string with whitespace removed at the ends. What does s.toUpperCase() do to s? Nothing: s is immutable. What does the toString method return for a String object? This string.

Klausimai pakartojimui: “sam”.equals(“Sam”) grąžins ? Koks bus reikšmės “sam”.compareTo(“Sam”) ženklas? Kokia bus s reikšmė? s = “dėdė”.replace(‘d’, ‘m’); Kaip pakeičia s eilutę metodo s.toUpperCase() iškvietimas ? Koks paprasčiausias būdas skaičių paversti eilute (tekstu) ? Name a simple way to convert a number into a string "" + num; Which class has a method for converting a String into an int? Integer (the method parseInt) Name a few Character methods that help identify the category to which a given char belongs. isDigit, isLetter, isUpperCase, isLowerCase, isWhitespace. What is the difference between the String and StringBuffer classes? StringBuffer objects are mutable; StringBuffer is more efficient for assembling a string from pieces. It has methods for inserting, appending, and deleting characters.