62
Strings and Strings and Strings Strings Manipulation Manipulation

Strings v.1.1

Embed Size (px)

DESCRIPTION

Strings and String manipulation in Java

Citation preview

Page 1: Strings v.1.1

Strings and Strings Strings and Strings ManipulationManipulation

Page 2: Strings v.1.1

ContentsContents

1.1. What Is String?What Is String?

2.2. Creating and Using StringsCreating and Using Strings

• Declaring, Creating, Reading and PrintingDeclaring, Creating, Reading and Printing

3.3. Manipulating StringsManipulating Strings

• Comparing, Concatenating, Searching, Comparing, Concatenating, Searching, Extracting Substrings, SplittingExtracting Substrings, Splitting

4.4. Other String OperationsOther String Operations

• Replacing Substrings, Deleting Substrings, Replacing Substrings, Deleting Substrings, Changing Character Casing, TrimmingChanging Character Casing, Trimming

Page 3: Strings v.1.1

Contents (2)Contents (2)

5.5. Building and Modifying StringsBuilding and Modifying Strings

• Using Using StringBuilderStringBuilder Class Class

6.6. Formatting StringsFormatting Strings

Page 4: Strings v.1.1

What Is String?What Is String?

Page 5: Strings v.1.1

What Is String?What Is String?

• StringString is:is:

• A sequence of charactersA sequence of characters

• Each character is a Unicode characterEach character is a Unicode character

• Represented by the Represented by the StringString ((java.lang.Stringjava.lang.String) data type in Java) data type in Java

• Example:Example:

String s = "Hello, Java";String s = "Hello, Java";

HH ee ll ll oo ,, JJ aa vv aassss

Page 6: Strings v.1.1

java.lang.Stringjava.lang.String

• We use We use java.lang.Stringjava.lang.String to work with to work with strings in Javastrings in Java

• String objects contain an immutable (read-String objects contain an immutable (read-only) sequence of charactersonly) sequence of characters

• Use Unicode in order to support multiple Use Unicode in order to support multiple languages and alphabetslanguages and alphabets

• Stores strings in the dynamic memory Stores strings in the dynamic memory (managed heap)(managed heap)

• java.lang.Stringjava.lang.String is class is class

• It is reference typeIt is reference type

Page 7: Strings v.1.1

java.lang.Stringjava.lang.String (2) (2)

• String objects are like arrays of characters String objects are like arrays of characters ((char[]char[]))• Have fixed length (Have fixed length (String.length()String.length()))

• Elements can be accessed by indexElements can be accessed by index• Using Using charAt()charAt() method method

• The index is in the range 0...length()-1The index is in the range 0...length()-1

String s = "Hello!";String s = "Hello!";int len = s.int len = s.llengthength()(); // len = 6; // len = 6char ch = schar ch = s.charAt(1).charAt(1); // ch = 'e'; // ch = 'e'

00 11 22 33 44 55

HH ee ll ll oo !!

index =index =index =index =

s.charAt(index) =s.charAt(index) =s.charAt(index) =s.charAt(index) =

Page 8: Strings v.1.1

Strings – First ExampleStrings – First Example

String s = "Stand up, stand up, Balkan superman.";String s = "Stand up, stand up, Balkan superman.";

System.out.printf("s = \"%s\"%n", s);System.out.printf("s = \"%s\"%n", s);System.out.printf("s.System.out.printf("s.llengthength()() = %d%n", s.length()); = %d%n", s.length());

for (int i = 0; i < s.length(); i++) {for (int i = 0; i < s.length(); i++) { System.out.printf("s[%d] = %c%n", i, s.charAt(i));System.out.printf("s[%d] = %c%n", i, s.charAt(i));}}

Page 9: Strings v.1.1

Strings – First ExampleStrings – First ExampleLive DemoLive Demo

Page 10: Strings v.1.1

Creating and Using StringsCreating and Using Strings

Declaring, Creating, Reading and Declaring, Creating, Reading and PrintingPrinting

Page 11: Strings v.1.1

Declaring StringsDeclaring Strings

• We use Java String class for declaring string We use Java String class for declaring string variables:variables:

String str;String str;

Page 12: Strings v.1.1

Creating StringsCreating Strings

• BeforBeforee initiali initializingzing a strin a stringg v vaariable iriable iss equa equall t too nunullll

• Strings can be initialized by:Strings can be initialized by:

• Assigning a Assigning a stristrinngg literal to the string variable literal to the string variable

• Assigning the value of another string variableAssigning the value of another string variable

• Assigning the result of operation of type Assigning the result of operation of type stringstring

Page 13: Strings v.1.1

Creating Strings (2)Creating Strings (2)

• Not initialized variables has value of Not initialized variables has value of nullnull

• Assigning a Assigning a stristrinngg literal literal

• Assigning another string variableAssigning another string variable

• Assigning the result of string operationAssigning the result of string operation

SString s; tring s; // s // s is is equal to nullequal to null

StString sring s = "I am string literal!"; = "I am string literal!";

SString string s2 = s;2 = s;

String s = "I'm " + 42 + " years old.";String s = "I'm " + 42 + " years old.";

Page 14: Strings v.1.1

Reading And Printing StringsReading And Printing Strings

• Reading strings from the consoleReading strings from the console

• Use the method Use the method input.nextLine()input.nextLine()

String s = input.nextLine();String s = input.nextLine();

• Printing strings to the consolePrinting strings to the console

• Use the methods Use the methods print()print() , , println()println() and and printf()printf()

• Printing strings to the consolePrinting strings to the console

• Use the methods Use the methods print()print() , , println()println() and and printf()printf()

System.out.print("Please enter your name: "); System.out.print("Please enter your name: "); String name = input.nextLine();String name = input.nextLine();System.out.printf("Hello, %s!%n", name);System.out.printf("Hello, %s!%n", name);

Page 15: Strings v.1.1

Reading and Reading and Printing StringsPrinting Strings

Live DemoLive Demo

Page 16: Strings v.1.1

Manipulating StringsManipulating Strings

Comparing, Concatenating, Comparing, Concatenating, Searching, Extracting Substrings, Searching, Extracting Substrings,

SplittingSplitting

Page 17: Strings v.1.1

Comparing StringsComparing Strings

• There are a number of ways to compaThere are a number of ways to compare two re two strings:strings:

• DDictionary-based string comparisonictionary-based string comparison

• CCase-insensitivease-insensitive

• Case-sensitiveCase-sensitive

int result = str1.compareToIgnoreCase(str2);int result = str1.compareToIgnoreCase(str2);// result == 0 if str1 equals str2// result == 0 if str1 equals str2// result < 0 if str1 if before str2// result < 0 if str1 if before str2// result > 0 if str1 if after str2// result > 0 if str1 if after str2

str1.compareTo(str2);str1.compareTo(str2);

Page 18: Strings v.1.1

Comparing Strings (2)Comparing Strings (2)

• Equality checking by Equality checking by equalsIgnoreCaseequalsIgnoreCase()()

• Performs cPerforms case-ase-ininsensitivesensitive compare compare

• Returns Returns booleanboolean value value

• TThehe case-sensitive case-sensitive equalsequals()() method method

if (str1.equalsIgnoreCase(str2)){if (str1.equalsIgnoreCase(str2)){ … …}}

if (str1.equals(str2)){if (str1.equals(str2)){ … …}}

Page 19: Strings v.1.1

Comparing Strings (3)Comparing Strings (3)

• Operators == and != does not check for equality!Operators == and != does not check for equality!

• These operators returns These operators returns booleanboolean value, but check value, but check if the addresses of the object are equalif the addresses of the object are equal

• Use equals() and Use equals() and equalsIgnoreCase()equalsIgnoreCase() instead instead

String str1 = new String("Hello");String str1 = new String("Hello");String str2 = str1;String str2 = str1;System.out.println((str1==str2)); // trueSystem.out.println((str1==str2)); // true

String str1 = "Hello";String str1 = "Hello";String str2 = "Hello";String str2 = "Hello";System.out.println((str1==str2)); // trueSystem.out.println((str1==str2)); // true!!!!!!

String str1 = new String("Hello");String str1 = new String("Hello");String str2 = new String("Hello");String str2 = new String("Hello");System.out.println((str1==str2)); // This is falseSystem.out.println((str1==str2)); // This is false!!

Page 20: Strings v.1.1

Comparing Strings – Example Comparing Strings – Example

• Finding the first in a lexicographical order Finding the first in a lexicographical order string from a given list of stringsstring from a given list of strings

String[] towns = {"Sofia", "Varna", "Plovdiv",String[] towns = {"Sofia", "Varna", "Plovdiv","Pleven", "Bourgas", "Rousse", "Yambol"};"Pleven", "Bourgas", "Rousse", "Yambol"};

String firstTown = towns[0];String firstTown = towns[0];for (int i=1; i<towns.for (int i=1; i<towns.llength; i++) {ength; i++) { String currentTown = towns[i];String currentTown = towns[i]; if (currentTown.compareTo(firstTown) < 0) {if (currentTown.compareTo(firstTown) < 0) { firstTown = currentTown;firstTown = currentTown; }}}}System.out.println("First town: " + firstTown);System.out.println("First town: " + firstTown);

Page 21: Strings v.1.1

Comparing StringsComparing Strings

Live DemoLive Demo

Page 22: Strings v.1.1

Concatenating StringsConcatenating Strings

• There are two ways to combine stringsThere are two ways to combine strings::

• UUsing sing the the cconconcat()at() methodmethod

• UsingUsing the the ++ or the or the +=+= operator operator

• Any object can be appended to stringAny object can be appended to string

SString str = tring str = str1.str1.cconcat(str2);oncat(str2);

String str = str1 + str2 + str3;String str = str1 + str2 + str3;String str += str1;String str += str1;

SString tring nname = "ame = "PeterPeter";";intint ageage = = 2222;;SString tring ss = = namename + " " + + " " + ageage;; // // "Peter 22" "Peter 22"

Page 23: Strings v.1.1

Concatenating Strings – Concatenating Strings – ExampleExample

String firstName = "Svetlin";String firstName = "Svetlin";String lastName = "Nakov";String lastName = "Nakov";

String fullName = firstName + " " + lastName;String fullName = firstName + " " + lastName;System.out.println(fullName);System.out.println(fullName);

int age = 2int age = 266;;

String nameAndAge = "Name: " + fullName + String nameAndAge = "Name: " + fullName + "\nAge: " + age;"\nAge: " + age;

System.out.println(nameAndAge);System.out.println(nameAndAge);// Name: Svetlin Nakov// Name: Svetlin Nakov// Age: 2// Age: 266

Page 24: Strings v.1.1

Concatenating StringsConcatenating Strings

Live DemoLive Demo

Page 25: Strings v.1.1

Searching StringsSearching Strings

• FFindindinging a character a character or substring or substring within within givengiven string string• FFirstirst occurrenceoccurrence

• FFirstirst occurrenceoccurrence starting at given position starting at given position

• Last occurrenceLast occurrence

• Last occurrence before given positionLast occurrence before given position

iindexOf(ndexOf(SString str)tring str)

iindexOf(ndexOf(SString str, int tring str, int fromfromIndex)Index)

llastIndexOf(astIndexOf(SString)tring)

lastIndexOf(String, int fromIndex)lastIndexOf(String, int fromIndex)

Page 26: Strings v.1.1

Searching Strings – ExampleSearching Strings – Example

String str = "Java Programming Course";String str = "Java Programming Course";

int index = str.indexOf("Java"); // index = 0int index = str.indexOf("Java"); // index = 0index = str.indexOf("Course"); // index = 17index = str.indexOf("Course"); // index = 17index = str.indexOf("COURSE"); // index = -1index = str.indexOf("COURSE"); // index = -1// indexOf is case sensetive. -1 means not found// indexOf is case sensetive. -1 means not foundindex = str.indexOf("ram"); // index = 9index = str.indexOf("ram"); // index = 9index = str.indexOf("r"); // index = 6index = str.indexOf("r"); // index = 6index = str.indexOf("r", 7); // index = 9index = str.indexOf("r", 7); // index = 9index = str.indexOf("r", 10); // index = 20index = str.indexOf("r", 10); // index = 20

00 11 22 33 44 55 66 77 88 99 1010 1111 1212 ……

JJ aa vv aa PP rr oo gg rr aa mm mm ……

i =i =i =i =

s.charAt(i) =s.charAt(i) =s.charAt(i) =s.charAt(i) =

Page 27: Strings v.1.1

Searching StringsSearching Strings

Live DemoLive Demo

Page 28: Strings v.1.1

Extracting SubstringsExtracting Substrings

• Extracting substringsExtracting substrings• str.substring(int beginIndex, int endIndex)str.substring(int beginIndex, int endIndex)

•lastIndexlastIndex is not included is not included

• str.substring(int beginIndex)str.substring(int beginIndex)

SString filename = "C:tring filename = "C:\\\Pics\Pics\\\Rila2005.jpg";\Rila2005.jpg";SString name = filename.tring name = filename.ssububsstring(8,tring(8, 16 16););// name is Rila2005// name is Rila2005

SString filename = "C:tring filename = "C:\\\Pics\Pics\\\Summer2005.jpg";\Summer2005.jpg";SString nameAndExtension = filename.tring nameAndExtension = filename.ssububsstring(8);tring(8);// nameAndExtension is Rila2005// nameAndExtension is Rila2005.jpg.jpg

00 11 22 33 44 55 66 77 88 99 1010 1111 1212 1313 1414 1515 1616 1717 1818 1919

CC :: \\ \\ PP ii cc ss \\\\ RR ii ll aa 22 00 00 55 .. jj pp gg

Page 29: Strings v.1.1

Extracting SubstringsExtracting Substrings

Live DemoLive Demo

Page 30: Strings v.1.1

Splitting StringsSplitting Strings

• To split a string by given separator(s) use the To split a string by given separator(s) use the following method:following method:

• String regexString regex – String with special format– String with special format

• We can list the character which we want to We can list the character which we want to use for separator in square brackets […]use for separator in square brackets […]

String[] split(String regex)String[] split(String regex)

String[] parts = "Ivan; Petar,Gosho".split("[;,]");String[] parts = "Ivan; Petar,Gosho".split("[;,]");// this wil separate the stirng into three parts// this wil separate the stirng into three parts// "Ivan", " Petar" and "Gosho"// "Ivan", " Petar" and "Gosho"

Page 31: Strings v.1.1

Splitting Strings - ExampleSplitting Strings - Example

String listOfBeers = String listOfBeers = "Amstel, Zagorka, Tuborg, Becks.";"Amstel, Zagorka, Tuborg, Becks.";

String[] beers = listOfBeers.split("[ ,.]");String[] beers = listOfBeers.split("[ ,.]");System.out.println("Available beers are:");System.out.println("Available beers are:");for (String beer : beers) {for (String beer : beers) {

if (!"".equalsIgnoreCase(beer)) {if (!"".equalsIgnoreCase(beer)) {System.out.println(beer);System.out.println(beer);

}}}}

Page 32: Strings v.1.1

Splitting StringsSplitting Strings

Live DemoLive Demo

Page 33: Strings v.1.1

Other String OperationsOther String OperationsReplacing Substrings, Changing Replacing Substrings, Changing

Character Casing, TrimmingCharacter Casing, Trimming

Page 34: Strings v.1.1

Replacing SubstringsReplacing Substrings

• rreplace(eplace(SString, tring, SString)tring) – replaces all – replaces all occurrences of given string with anotheroccurrences of given string with another

• The result is new string (strings are immutable)The result is new string (strings are immutable)

String cocktail = "Vodka + Martini + Cherry";String cocktail = "Vodka + Martini + Cherry";String replaced = cocktail.replace("+", "and");String replaced = cocktail.replace("+", "and");// Vodka and Martini and Cherry// Vodka and Martini and Cherry

Page 35: Strings v.1.1

Changing Character CasingChanging Character Casing

• Using method Using method toLowerCase()toLowerCase()

• Using method Using method toUpperCase()toUpperCase()

SString alpha = "aBcDeFg";tring alpha = "aBcDeFg";SString lowerAlpha = alpha.tring lowerAlpha = alpha.ttoLoweroLowerCaseCase();(); //// abcdefgabcdefgSystem.out.println(lowerAlpha);System.out.println(lowerAlpha);

SString alpha = "aBcDeFg";tring alpha = "aBcDeFg";SString uppertring upperAAlpha = alpha.lpha = alpha.ttoUpperoUpperCaseCase();(); //// ABCDEFG ABCDEFGSystem.out.println(upperAlpha);System.out.println(upperAlpha);

Page 36: Strings v.1.1

Trimming White SpaceTrimming White Space

• Using method Using method trim()trim()

String s = " example of white space ";String s = " example of white space ";String clean = s.trim();String clean = s.trim();System.out.println(clean);System.out.println(clean);

Page 37: Strings v.1.1

Other String OperationsOther String OperationsLive DemoLive Demo

Page 38: Strings v.1.1

Building and Modifying Building and Modifying StringsStrings

Using Using StringBuilder StringBuilder CClasslass

Page 39: Strings v.1.1

Constructing StringsConstructing Strings

• Strings are immutableStrings are immutable• cconcat()oncat(), , rreplace()eplace(), , ttrim()rim(), ..., ... return return

new string, do not modify the old onenew string, do not modify the old one

• Do not use "Do not use "++" for strings in a loop!" for strings in a loop!

• It runs very inefficiently!It runs very inefficiently!

public public static sstatic string tring ddupChar(char ch, int count){upChar(char ch, int count){ SString result = "";tring result = ""; for (int i=0; i<count; i++)for (int i=0; i<count; i++) result += ch;result += ch; return result;return result;}} Bad practice. Bad practice.

Avoid this!Avoid this!Bad practice. Bad practice.

Avoid this!Avoid this!

Page 40: Strings v.1.1

Changing the Contents of a Changing the Contents of a String – String – StringBuilderStringBuilder

• Use the Use the java.lang.StringBuilderjava.lang.StringBuilder class class for modifiable strings of characters:for modifiable strings of characters:

• Use Use StringBuilderStringBuilder if you need to keep if you need to keep adding characters to a stringadding characters to a string

public static String public static String rreverseIt(String s) {everseIt(String s) { StringBuilder sb = new StringBuilder();StringBuilder sb = new StringBuilder(); for (int i = s.length()-1; i >= 0; i--)for (int i = s.length()-1; i >= 0; i--) sb.append(s.charAt(i));sb.append(s.charAt(i)); return sb.ToString();return sb.ToString();}}

Page 41: Strings v.1.1

The The StringBuildeStringBuilder Classr Class

• StringBuilderStringBuilder keeps a buffer memory, keeps a buffer memory, allocated in advanceallocated in advance

• Most operations use the buffer memory and Most operations use the buffer memory and do not allocate new objectsdo not allocate new objects

HH ee ll ll oo ,, JJ aa vv aa !!StringBuilderStringBuilder::

length() = 11length() = 11capacity() = 15capacity() = 15

StringBuilderStringBuilder::

length() = 11length() = 11capacity() = 15capacity() = 15 used bufferused buffer

(length())(length())used bufferused buffer(length())(length())

unusedunusedbufferbuffer

unusedunusedbufferbuffer

CapacityCapacityCapacityCapacity

Page 42: Strings v.1.1

The The StringBuildeStringBuilder Class (2)r Class (2)

• StringBuilder(int capacity)StringBuilder(int capacity) constructor allocates in advance constructor allocates in advance buffer memory of a given sizebuffer memory of a given size• By default 16 characters are allocatedBy default 16 characters are allocated

• capacity()capacity() holds the currently holds the currently allocated space (in characters)allocated space (in characters)

• charAt(int index)charAt(int index) gives access to gives access to the char value at given positionthe char value at given position

• length()length() hold the length of the string hold the length of the string in the bufferin the buffer

Page 43: Strings v.1.1

The The StringBuildeStringBuilder Class (3)r Class (3)

• append(append(……)) appends string or other object after appends string or other object after the last character in the bufferthe last character in the buffer

• deletedelete(int start, int (int start, int endend)) removes the removes the characters in given rangecharacters in given range

• iinsert(int nsert(int offsetoffset, , SString str)tring str) inserts inserts given string (or object) at given positiongiven string (or object) at given position

• replace(int start, int end, String replace(int start, int end, String str)str) replaces all occurrences of a substring replaces all occurrences of a substring with given stringwith given string

• ttoString()oString() converts the converts the StringBuilderStringBuilder to to StringString object object

Page 44: Strings v.1.1

StringBuilderStringBuilder – Example – Example

• Extracting all capital letters from a stringExtracting all capital letters from a string

public static String extractCapitals(String s) {public static String extractCapitals(String s) { StringBuilder result = new StringBuilder();StringBuilder result = new StringBuilder(); for (int i = 0; i < s.length(); i++) {for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i);char ch = s.charAt(i); if (Character.isUpperCase(ch)) {if (Character.isUpperCase(ch)) { result.append(ch);result.append(ch); }} }} return result.toString();return result.toString();}}

Page 45: Strings v.1.1

How the How the ++ Operator Does Operator Does String Concatenations?String Concatenations?

• Consider following string concatenation:Consider following string concatenation:

• It is equivalent to this code:It is equivalent to this code:

• Actually several new objects are created Actually several new objects are created and leaved to the garbage collectorand leaved to the garbage collector

• What happens when using What happens when using ++ in a loop? in a loop?

String result = str1 + str2;String result = str1 + str2;

StringBuffer sb = new StringBuffer();StringBuffer sb = new StringBuffer();sb.sb.aappend(str1);ppend(str1);sb.sb.aappend(str2);ppend(str2);SString result = sb.tring result = sb.ttoString();oString();

Page 46: Strings v.1.1

Using Using StringBuilderStringBuilder

Live DemoLive Demo

Page 47: Strings v.1.1

Formatting StringsFormatting StringsUsing Using ttoString()oString() and and String.String.fformat()ormat()

Page 48: Strings v.1.1

Method Method toString()toString()

• All classes have this public virtual methodAll classes have this public virtual method

• Returns a human-readable, culture-sensitive Returns a human-readable, culture-sensitive string representing the objectstring representing the object

• Most Java Platform types have own Most Java Platform types have own implementation of implementation of ttoString()oString()

Page 49: Strings v.1.1

Method Method String.format()String.format()

• AppliesApplies templatetemplatess for for formatting formatting stringstringss

• Placeholders are used for dynamic textPlaceholders are used for dynamic text

• Like Like System.out.printf(System.out.printf(……))

String template = "If I were %s, I would %s.";String template = "If I were %s, I would %s.";String sentence1 = String.format(String sentence1 = String.format( template, "developer", "know Java");template, "developer", "know Java");System.out.println(sentence1);System.out.println(sentence1);// If I were developer, I would know // If I were developer, I would know JavaJava..

String sentence2 = String.format(String sentence2 = String.format( template, "elephant", "weigh 4500 kg");template, "elephant", "weigh 4500 kg");System.out.println(sentence2);System.out.println(sentence2);// If I were elephant, I would weigh 4500 kg.// If I were elephant, I would weigh 4500 kg.

Page 50: Strings v.1.1

Formatting DatesFormatting Dates

• When we print Dates we use prefix t or TWhen we print Dates we use prefix t or T

• d, ed, e – – day (with/without leading zero)day (with/without leading zero)

• mm – – monthmonth

• y, Y y, Y – – year (2 or 4 digits)year (2 or 4 digits)

• H, H, MM, , SS – – hour, minute, secondhour, minute, second

Date Date nownow = (new GregorianCalendar()).getTime(); = (new GregorianCalendar()).getTime();System.out.printf("Now is " + System.out.printf("Now is " +

"%1$td.%1$tm.%1$tY %1$tH:%1$tM:%1$tS", "%1$td.%1$tm.%1$tY %1$tH:%1$tM:%1$tS", nownow););// Now is 23.05.2006 21:09:32// Now is 23.05.2006 21:09:32

Page 51: Strings v.1.1

Formatting StringsFormatting StringsLive DemoLive Demo

Page 52: Strings v.1.1

SummarySummary

• Strings are immutable sequences of chars Strings are immutable sequences of chars (instances of (instances of java.lang.Stringjava.lang.String))• Declared by the class Declared by the class StringString in Java in Java

• Can be initialized by string literalsCan be initialized by string literals

• The most important string processing The most important string processing members are:members are:• length(),length(), charAt()charAt(), , compare(str1, compare(str1, str2)str2), , indexOf(str)indexOf(str), , lastIndexOf(str)lastIndexOf(str), , subsubsstring(startIndex, endIndex)tring(startIndex, endIndex), , replace(oldStr, newStr)replace(oldStr, newStr), , toLower()toLower(), , toUpper()toUpper(), , trim()trim()

Page 53: Strings v.1.1

Summary (2)Summary (2)

• Objects can be converted to strings and can Objects can be converted to strings and can be formatted in different styles (be formatted in different styles (ttoStringoString()() method)method)

• Strings can be constructed by using Strings can be constructed by using placeholders and formatting strings placeholders and formatting strings ((String.String.fformatormat((……))))

Page 54: Strings v.1.1

ExercisesExercises

1.1. Write a program that reads a string, reverses it Write a program that reads a string, reverses it and prints it on the console. Example: "sample" and prints it on the console. Example: "sample" " "elpmaselpmas".".

2.2. Write a program to check if in a given Write a program to check if in a given expression the brackets are put correctly. expression the brackets are put correctly. Example of correct expression: ((a+b)/5-d). Example of correct expression: ((a+b)/5-d). Example of incorrect expression: Example of incorrect expression: )(a+b)).)(a+b)).

Page 55: Strings v.1.1

Exercises (2)Exercises (2)

3.3. Write a program that finds how many times a Write a program that finds how many times a substring is contained in a given text substring is contained in a given text (perform case insensitive search).(perform case insensitive search).

Example: The target substring is "in". The Example: The target substring is "in". The text is as follows:text is as follows:

The result is: 9.The result is: 9.

We are living in a yellow submarine. We don't We are living in a yellow submarine. We don't have anything else. Inside the submarine is have anything else. Inside the submarine is very tight. So we are drinking all the day. very tight. So we are drinking all the day. We will move out of it in 5 days.We will move out of it in 5 days.

Page 56: Strings v.1.1

Exercises (3)Exercises (3)

4.4. You are given a text. Write a program that You are given a text. Write a program that changes the text in all regions identified by changes the text in all regions identified by the tagsthe tags <upcase><upcase> andand </upcase></upcase> to to uppercase. The tags cannot be nested. uppercase. The tags cannot be nested. Example:Example:

The expected result:The expected result:

We are living in a We are living in a <upcase><upcase>yellow yellow submarine</upcase>. We don't have submarine</upcase>. We don't have <upcase>anything</upcase><upcase>anything</upcase> else else..

We are living in a We are living in a YELLOW SUBMARINEYELLOW SUBMARINE. We don't . We don't have have ANYTHINGANYTHING else. else.

Page 57: Strings v.1.1

Exercises (4)Exercises (4)

5.5. Write a program that parses an URL address Write a program that parses an URL address given in the format:given in the format:

and extracts from it the and extracts from it the [protocol][protocol], , [server][server] andand [resource][resource] elements. For elements. For example from the URL example from the URL http://www.devbg.org/forum/index.phphttp://www.devbg.org/forum/index.php following information should be extracted: following information should be extracted: [protocol][protocol] = " = "httphttp"", , [server][server] = = ""www.devbg.orgwww.devbg.org"", , [resource][resource] = = ""/forum/index.php/forum/index.php""

[protocol]://[server]/[resource][protocol]://[server]/[resource]

Page 58: Strings v.1.1

Exercises (5)Exercises (5)

6.6. Write a program that extracts from a given Write a program that extracts from a given text all the sentences that contain given word. text all the sentences that contain given word. Example: The word is "in". The text is:Example: The word is "in". The text is:

The expected result is:The expected result is:

Consider that the sentences are separated by Consider that the sentences are separated by "." and the words – by non-letter symbols."." and the words – by non-letter symbols.

We are living in a yellow submarine. We don't We are living in a yellow submarine. We don't have anything else. Inside the submarine is have anything else. Inside the submarine is very tight. So we are drinking all the day. very tight. So we are drinking all the day. We will move out of it in 5 days.We will move out of it in 5 days.

We are living in a yellow submarine.We are living in a yellow submarine.We will move out of it in 5 days.We will move out of it in 5 days.

Page 59: Strings v.1.1

Exercises (6)Exercises (6)

7.7. We are given a string containing a list of We are given a string containing a list of forbidden words and a text containing some forbidden words and a text containing some of these words. Write a program that replaces of these words. Write a program that replaces the forbidden words with asterisks. Example:the forbidden words with asterisks. Example:

Words: Words: "Java, JVM, Microsoft""Java, JVM, Microsoft"

The expected result:The expected result:

Microsoft announced its next generation Java Microsoft announced its next generation Java compiler today. It uses advanced parser and compiler today. It uses advanced parser and special optimizer for the Microsoft JVM.special optimizer for the Microsoft JVM.

********* announced its next generation **** ********* announced its next generation **** compiler today. It uses advanced parser and compiler today. It uses advanced parser and special optimizer for the ********* ***.special optimizer for the ********* ***.

Page 60: Strings v.1.1

Exercises (7)Exercises (7)

8.8. WriteWrite a a prog progrram that reads am that reads a a string from the string from the consoleconsole and lists all the different letters in the and lists all the different letters in the string along with information how many times string along with information how many times each letter is foundeach letter is found. .

9.9. WriteWrite a a prog progrram that reads am that reads a a string from the string from the consoleconsole and lists all the different words in the and lists all the different words in the string with information how many times each string with information how many times each word is found.word is found.

10.10. Write a program that Write a program that reads a string from the reads a string from the console and console and replacereplacess all all series of consecutive series of consecutive identical identical lettersletters with with a single onea single one.. E Examxampplele:: "aaaaabbbbbcdddeeeedssaa" -> "abcdedsa""aaaaabbbbbcdddeeeedssaa" -> "abcdedsa"..

Page 61: Strings v.1.1

Exercises (8)Exercises (8)

11.11. Write a program that readWrite a program that readss a a list of list of words words,, separatedseparated by by spaces (' ') spaces (' ') , and print, and printss thethe list list in in an an alphabetical order.alphabetical order.

12.12. Write a program that lets the user input a Write a program that lets the user input a string of maximum 20 characters. If the length string of maximum 20 characters. If the length of the string is less, the rest of the characters of the string is less, the rest of the characters should be filled with '*'. Print the string into the should be filled with '*'. Print the string into the console.console.

Page 62: Strings v.1.1

Exercises (9)Exercises (9)

13.13. * Write a program that encodes and * Write a program that encodes and decodes a string using an encryption key decodes a string using an encryption key (cipher). The key consists of a sequence of (cipher). The key consists of a sequence of characters.characters. The encoding/decoding is done The encoding/decoding is done by performing XOR (exclusive or) operation by performing XOR (exclusive or) operation over the first letter of the string with the over the first letter of the string with the first of the key, the second – with the first of the key, the second – with the second, etc. When the last key character is second, etc. When the last key character is used, the next is the first.used, the next is the first.