1 / 37

JAVA Programcılığı 2.1.2

JAVA Programcılığı 2.1.2. Ali R+ SARAL. Ders Planı 2.1.2. Operations on Strings Accessing String Characters Extracting String Characters Searching Strings for Characters Searching for Substrings Extracting Substrings Tokenizing a String

druce
Download Presentation

JAVA Programcılığı 2.1.2

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. JAVA Programcılığı 2.1.2 Ali R+ SARAL

  2. Ders Planı 2.1.2 • Operations on Strings Accessing String Characters Extracting String Characters Searching Strings for Characters Searching for Substrings Extracting Substrings Tokenizing a String • Modified Versions of String Objects

  3. Ders Planı 2.1.2 • Mutable Strings StringBuffer Objects Changing , Adding , Appending to StringBuffer Object Finding, Replacing a Substring in the Buffer Inserting Extracting Strings from a Mutable String Other Mutable String Operations

  4. Accessing String CharactersYazı Harflerine Erişim

  5. Extracting String CharactersEXAMPLE - Try It Out Getting at Characters in a String public class StringCharacters { public static void main(String[] args) { // Text string to be analyzed String text = “To be or not to be, that is the question;” +”Whether ‘tis nobler in the mind to suffer” +” the slings and arrows of outrageous fortune,” +” or to take arms against a sea of troubles,” +” and by opposing end them?”; int spaces = 0, // Count of spaces vowels = 0, // Count of vowels letters = 0; // Count of letters // Analyze all the characters in the string int textLength = text.length(); // Get string length

  6. Extracting String CharactersEXAMPLE - Try It Out Getting at Characters in a String for(int i = 0; i < textLength; i++) { // Check for vowels char ch = Character.toLowerCase(text.charAt(i)); if(ch == ‘a’ || ch == ‘e’ || ch == ‘i’ || ch == ‘o’ || ch == ‘u’) { vowels++; } //Check for letters if(Character.isLetter(ch)) { letters++; } // Check for spaces if(Character.isWhitespace(ch)) { spaces++; } } System.out.println(“The text contained vowels: “ + vowels + “\n” + “ consonants: “ + (letters-vowels) + “\n”+ “ spaces: “ + spaces); } }

  7. Searching Strings for CharactersYazılarda Harf Arayış • int index = 0; // Position of character in the string • index = text.indexOf(‘a’); // Find first index position containing ‘a’ • index = text.lastIndexOf(‘a’); // Find last index position containing ‘a’ • index = text.indexOf(‘a’, startIndex);

  8. Searching Strings for CharactersYazılarda Harf Arayış

  9. EXAMPLE - Try It Out Exciting Concordance Entries public class FindCharacters { public static void main(String[] args) { // Text string to be analyzed String text = “To be or not to be, that is the question;” + “ Whether ‘tis nobler in the mind to suffer” + “ the slings and arrows of outrageous fortune,” + “ or to take arms against a sea of troubles,” + “ and by opposing end them?”; int andCount = 0; // Number of and’s int theCount = 0; // Number of the’s int index = -1; // Current index position String andStr = “and”; // Search substring String theStr = “the”; // Search substring

  10. EXAMPLE - Try It Out Exciting Concordance Entries // Search forwards for “and” index = text.indexOf(andStr); // Find first ‘and’ while(index >= 0) { ++andCount; index += andStr.length(); // Step to position after last ‘and’ index = text.indexOf(andStr, index); } // Search backwards for “the” index = text.lastIndexOf(theStr); // Find last ‘the’ while(index >= 0) { ++theCount; index -= theStr.length(); // Step to position before last ‘the’ index = text.lastIndexOf(theStr, index); } System.out.println(“The text contains “ + andCount + “ ands\n” + “The text contains “ + theCount + “ thes”); } }

  11. Extracting SubstringsYazıların Alt Kısımlarını ÇıkarmakEXAMPLE - Try It Out Word for Word public class ExtractSubstrings { public static void main(String[] args) { String text = “To be or not to be”; // String to be segmented int count = 0; // Number of substrings char separator = ‘ ‘; // Substring separator // Determine the number of substrings int index = 0; do { ++count; ++index; // Move past last position index = text.indexOf(separator, index); } while (index != -1);

  12. Extracting SubstringsEXAMPLE - Try It Out Word for Word // Extract the substring into an array String[] subStr = new String[count]; // Allocate for substrings index = 0; // Substring start index int endIndex = 0; // Substring end index for(int i = 0; i < count; i++) { endIndex = text.indexOf(separator,index); // Find next separator if(endIndex == -1) { // If it is not found subStr[i] = text.substring(index); // extract to the end } else { // otherwise subStr[i] = text.substring(index, endIndex); // to end index } index = endIndex + 1; // Set start for next cycle } // Display the substrings for(String s : subStr) { // For each string in subStr System.out.println(s); // display it } } }

  13. Tokenizing a String Bir Yazıyı Kısımlarına Ayırmak • String text = “to be or not to be, that is the question.”; • String[] words = text.split(“[, .]”, 0); // Delimiters are comma, space, or period • String[] words = text.split(“[, .]”); // Delimiters are comma, space, or period

  14. EXAMPLE - Try It Out Using a Tokenizer public class StringTokenizing { public static void main(String[] args) { String text = “To be or not to be, that is the question.”; // String to segment String delimiters = “[, .]”; // Delimiters are comma, space, and period int[] limits = {0, -1}; // Limit values to try // Analyze the string for(int limit : limits) { System.out.println(“\nAnalysis with limit = “ + limit); String[] tokens = text.split(delimiters, limit); System.out.println(“Number of tokens: “ + tokens.length); for(String token : tokens) { System.out.println(token); } } } }

  15. Modified Versions of String Objects Yazı Nesnelerinin Değişime Uğramış Halleri • String newText = text.replace(‘ ‘, ‘/’); // Modify the string text • String sample = “ This is a string “; • String result = sample.trim();

  16. Creating Character Arrays from String Objects Yazı Nesnelerinden Harf Dizileri Çıkarış • String text = “To be or not to be”; • char[] textArray = text.toCharArray(); // Create the array from the string

  17. Using the Collection-Based for Loop with a String • String phrase = “The quick brown fox jumped over the lazy dog.”; • int vowels = 0; • for(char ch : phrase.toCharArray()) { • ch = Character.toLowerCase(ch); • if(ch == ‘a’ || ch == ‘e’ || ch == ‘i’ || ch == ‘o’ || ch == ‘u’) { • ++vowels; • } • } • System.out.println(“The phrase contains “ + vowels + “ vowels.”);

  18. Obtaining the Characters in a String as an Array of BytesBir Yazıdan Harfleri Bir Byte Dizisi Olarak Almak • String text = “To be or not to be”; // Define a string • byte[] textArray = text.getBytes(); // Get equivalent byte array

  19. Creating String Objects from Character Arrays Harf dizilerinden Yazı Nesneleri Yaratış • char[] textArray = {‘T’, ‘o’, ‘ ‘, ‘b’, ‘e’, ‘ ‘, ‘o’, ‘r’, ‘ ‘, • ‘n’, ‘o’, ‘t’, ‘ ‘, ‘t’, ‘o’, ‘ ‘, ‘b’, ‘e’ }; • String text = String.copyValueOf(textArray); • String text = new String(textArray); • String text = String.copyValueOf(textArray, 9, 3); • String text = new String(textArray, 9, 3);

  20. Mutable Strings Değiştirilebilir Yazılar • String objects cannot be changed, but you have been creating strings that are combinations and modifications • of existing String objects, so how is this done? Java has two other standard classes that encapsulate • strings, the StringBuffer class and the StringBuilder class, and both StringBuffer and • StringBuilder objects can be altered directly.

  21. Mutable Strings Değiştirilebilir Yazılar • Strings that can be changed are referred to as mutable strings, in contrast to String objects that are immutable strings. Java uses objects of the StringBuffer • class type internally to perform many of the operations that involve combining String objects. Once the • required string has been formed as a StringBuffer object, it is then converted to an object of type • String. • In terms of the operations these two • classes provide, there is no difference, but StringBuffer objects are safe for use by multiple threads, • whereas StringBuilder objects are not.

  22. Creating StringBuffer ObjectsStringBuffer Nesneleri Yaratış • StringBuffer aString = new StringBuffer(“A stitch in time”); • String phrase = “Experience is what you get when you’re expecting something else.”; • StringBuffer buffer = new StringBuffer(phrase); • StringBuffer myString = null; • myString = new StringBuffer(“Many a mickle makes a muckle”); • StringBuffer aString = myString;

  23. The Capacity of a StringBuffer Object • StringBuffer aString = new StringBuffer(“A stitch in time”); • int theLength = aString.length(); • When you create a StringBuffer object from an existing string, the capacity will be the length of the string plus 16. Both the capacity and the length are in units of Unicode characters, so twice as many bytes will be occupied in memory.

  24. The Capacity of a StringBuffer Object • A String object is always a fixed string, so capacity is irrelevant—it is always just enough to hold the • characters in the string. A StringBuffer object on the other hand is a container in which you can store • a string of any length, and it has a capacity at any given instant for storing a string up to a given size. • Although you can set the capacity, it is unimportant in the sense that it is just a measure of how much • memory is available to store Unicode characters at this particular point in time. You can get by without worrying about the capacity of a StringBuffer object at all since the capacity required to cope with what your program is doing will always be provided automatically. It just gets increased as necessary.

  25. The Capacity of a StringBuffer Object • int theCapacity = aString.capacity(); • The ensureCapacity() method enables you to change the default capacity of a StringBuffer object. • You specify the minimum capacity you need as the argument to the method. For example: • aString.ensureCapacity(40);

  26. Changing the String Length for a StringBuffer Object • aString.setLength(8); • aString.setLength(16); • Now aString will contain the string • “A stitch\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000”

  27. Adding to a StringBuffer Object • StringBuffer aString = new StringBuffer(“A stitch in time”); • aString.append(“ saves nine”); • StringBuffer bString = aString.append(“ saves nine”); • StringBuffer proverb = new StringBuffer(); // Capacity is 16 • proverb.append(“Many”).append(“ hands”).append(“ make”).append(“ light”).append(“ work.”);

  28. Appending a Substring • StringBuffer buf = new StringBuffer(“Hard “); • String aString = “Waxworks”; • buf.append(aString, 3, 4);

  29. Appending Basic Types • StringBuffer buf = new StringBuffer(“The number is “); • long number = 999; • buf.append(number); • buf.append(12.34); • the object buf will contain “The number is 99912.34”.

  30. Appending Basic Types • char[] text = { ‘i’, ‘s’, ‘ ‘, ‘e’, ‘x’, ‘a’, ‘c’, ‘t’, ‘l’, ‘y’}; • buf.append(text, 2, 8);

  31. Finding the Position of a Substring • StringBuffer phrase = new StringBuffer(“one two three four”); • int position = phrase.lastIndexOf(“three”); • position = phrase.lastIndexOf(“three”, 6);

  32. Replacing a Substring in the Buffer • StringBuffer phrase = new StringBuffer(“one two three four”); • String substring = “two”; • String replacement = “twenty”; • int position = phrase.lastIndexOf(substring); // Find start of “two” • phrase.replace(position, position+substring.length(), replacement);

  33. Inserting Strings • buf.insert(4, “ old”); • insert(int index, char[] str, int offset, int length)

  34. Extracting Characters from a Mutable String • The StringBuffer class includes the charAt() and getChars() methods, both of which work in the • same way as the methods of the same name in the String class which you’ve already seen.

  35. Other Mutable String Operations • buf.setCharAt(3, ‘Z’); • StringBuffer phrase = new StringBuffer(“When the boats come in”); • phrase.deleteCharAt(10); • phrase.delete(5, 9); (5,6,7,8) are deleted • StringBuffer palindrome = new StringBuffer(“so many dynamos”); • palindrome.reverse();

  36. Creating a String Object from a StringBuffer Object • String saying = proverb.toString(); • String saying = “Many” + “ hands” + “ make” + “ light” + “ work”; • the compiler will implement this as: • String saying = new StringBuffer().append(“Many”).append(“ hands”). • append(“ make”).append(“ light”).

  37. Try It Out Using a StringBuffer Object to Assemble a String public class UseStringBuffer { public static void main(String[] args) { StringBuffer sentence = new StringBuffer(20); System.out.println(“\nStringBuffer object capacity is “+ sentence.capacity()+ “ and string length is “+sentence.length()); // Append all the words to the StringBuffer object String[] words = {“Too” , “many”, “cooks”, “spoil”, “the” , “broth”}; sentence.append(words[0]); for(int i = 1 ; i<words.length ; i++) { sentence.append(‘ ‘).append(words[i]); } // Show the result System.out.println(“\nString in StringBuffer object is:\n” + sentence.toString()); System.out.println(“StringBuffer object capacity is now “+ sentence.capacity()+ “ and string length is “+sentence.length()); // Now modify the string by inserting characters sentence.insert(sentence.lastIndexOf(“cooks”)+4,”ie”); sentence.insert(sentence.lastIndexOf(“broth”)+5, “er”); System.out.println(“\nString in StringBuffer object is:\n” + sentence); System.out.println(“StringBuffer object capacity is now “+ sentence.capacity()+ “ and string length is “+sentence.length()); } }

More Related