Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "String klasė http://www.fatih.edu.tr/~moktay/2009/spring/ceng104/The.String.Class.ppt."— Presentation transcript:

1 String klasė

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

3 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.

4 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ų.

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

6 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ą.

7 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

8 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"

9 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

10 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

11 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

12 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”

13 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'

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

15 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”

16 indexOf metodas ᆪ j ᆲ ᆲ ᆲ String vardas =“Prezidentas Valdas Adamkus";
j String vardas =“Prezidentas Valdas Adamkus"; vardas.indexOf (‘P'); vardas.indexOf (‘e'); vardas.indexOf (“Vadas"); vardas.indexOf (‘e', 3); vardas.indexOf (“Jonas"); vardas.lastIndexOf (‘a'); 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)

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

18 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… }

19 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

20 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.

21 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.

22 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.

23 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.

24 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” 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”

25 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.

26 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.

27 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.

28 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.


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

Similar presentations


Ads by Google