60

String and string manipulation x

Embed Size (px)

Citation preview

Page 1: String and string manipulation x
Page 2: String and string manipulation x

STRINGS AND STRINGS MANIPULATION

Page 3: String and string manipulation x

CONTENTS

1. What Is String?

2. Creating and Using Strings

• Declaring, Creating, Reading and Printing

3. Manipulating Strings

• Comparing, Concatenating, Searching, Extracting Substrings, Splitting

4. Other String Operations

• Replacing Substrings, Deleting Substrings, Changing Character Casing,

Trimming

Page 4: String and string manipulation x

CONTENTS

5. Building and Modifying Strings

• Using StringBuilder Class

6. Formatting Strings

Page 5: String and string manipulation x

WHAT IS STRING?

Page 6: String and string manipulation x

FREQUENTLY ASKED QUESTIONS FAQ

• What is string ?

• Why string is final?

• What are the ways to declare and initialize the String Object?

• What is the difference b/w Reference values and literal strings?

• What is the difference b/w + opretor and concat() method?

• What is the effect when comparing strings with == and equals() ?

• What is Difference b/w String class and String Buffer?

• What is String pool in Java?

• What does intern() method do in Java?

• Why String is thread-safe in Java?

• What is the difference b/w System.out.println(1+2+” text”) and System.out.println(” text”+1+2) ?

Page 7: String and string manipulation x

WHAT IS STRING?

• String is:

• A sequence of characters

• Each character is a Unicode character

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

• Example:

String s = "Hello, Java";

H e l l o , J a v as

Page 8: String and string manipulation x

JAVA.LANG.STRING

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

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

• Use Unicode in order to support multiple languages and alphabets

• Stores strings in the dynamic memory (managed heap)

• java.lang.String is class

• It is reference type

Page 9: String and string manipulation x

JAVA.LANG.STRING• String objects are like arrays of characters (char[])

• Have fixed length (String.length())

• Elements can be accessed by index

• Using charAt() method

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

String s = "Hello!";

int len = s.length(); // len = 6

char ch = s.charAt(1); // ch = 'e„`

0 1 2 3 4 5

H e l l o !

index =

s.charAt(index) =

Page 10: String and string manipulation x

STRINGS – FIRST EXAMPLE

String s = “Hidaya Institute of Science & Tchnology.";

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

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

for (int i = 0; i < s.length(); i++) {

System.out.printf("s[%d] = %c%n", i, s.charAt(i));

}

Page 11: String and string manipulation x

STRINGS – FIRST EXAMPLELive Demo

Page 12: String and string manipulation x

Creating and Using Strings

Declaring, Creating, Reading and Printing

Page 13: String and string manipulation x

DECLARING STRINGS

• We use Java String class for declaring string variables:

String str;

Page 14: String and string manipulation x

CREATING STRINGS

• Before initializing a string variable is equal to null

• Strings can be initialized by:

• Assigning a string literal to the string variable

• Assigning the value of another string variable

• Assigning the result of operation of type string

Page 15: String and string manipulation x

CREATING STRINGS (2)

• Not initialized variables has value of null

• Assigning a string literal

• Assigning another string variable

• Assigning the result of string operation

String s; // s is equal to null

String s = "I am string literal!";

String s2 = s;

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

Page 16: String and string manipulation x

READING AND PRINTING STRINGS

• Reading strings from the console

• Use the method input.nextLine()

String s = input.nextLine();

• Printng Strings to the console

• Use methods print() and println()

System.out.print("Please enter your name: ");

String name = input.nextLine();

System.out.printf("Hello, %s!%n", name);

Page 17: String and string manipulation x

MANIPULATING STRINGSComparing, Concatenating, Searching, Extracting Substrings, Splitting

Page 18: String and string manipulation x

COMPARING STRINGS

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

• Dictionary-based string comparison

• Case-insensitive

• Case-sensitive

int result = str1.compareToIgnoreCase(str2);

// result == 0 if str1 equals str2

// result < 0 if str1 if before str2

// result > 0 if str1 if after str2

str1.compareTo(str2);

Page 19: String and string manipulation x

COMPARING STRINGS (2)

• Equality checking by equalsIgnoreCase()

• Performs case-insensitive compare

• Returns boolean value

• The case-sensitive equals() method

if (str1.equalsIgnoreCase(str2)){

}

if (str1.equals(str2)){

}

Page 20: String and string manipulation x

COMPARING STRINGS (3)

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

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

• Use equals() and equalsIgnoreCase() instead

String str1 = new String("Hello");

String str2 = str1;

System.out.println((str1==str2)); // true

String str1 = "Hello";

String str2 = "Hello";

System.out.println((str1==str2)); // true!!!

String str1 = new String("Hello");

String str2 = new String("Hello");

System.out.println((str1==str2)); // This is false!

Page 21: String and string manipulation x

COMPARING STRINGS – EXAMPLE

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

String[] towns = {"Jamshoro", "hyderabad",

"Qasimabad","Latifabad", "Kotri", "Heerabad"};

String firstTown = towns[0];

for (int i=1; i<towns.length; i++) {

String currentTown = towns[i];

if (currentTown.compareTo(firstTown) < 0) {

firstTown = currentTown;

}

}

System.out.println("First town: " + firstTown);

Page 22: String and string manipulation x

COMPARING STRINGSLive Demo

Page 23: String and string manipulation x

CONCATENATING STRINGS• There are two ways to combine strings:

• Using the concat() method

• Using the + or the += operator

• Any object can be appended to string

String str = str1.concat(str2);

String str = str1 + str2 + str3;

String str += str1;

String name = "Peter";

int age = 22;

String s = name + " " + age; // "Peter 22"

Page 24: String and string manipulation x

CONCATENATING STRINGS – EXAMPLE

String firstName = "Shahjahan";

String lastName = "Samoon";

String fullName = firstName + " " + lastName;

int age = 23;

String nameAndAge = "Name: " + fullName +

"\nAge: " + age;

System.out.println(nameAndAge);

// Name: Shahjahan Samoon

// Age: 23

Page 25: String and string manipulation x

CONCATENATING STRINGSLive Demo

Page 26: String and string manipulation x

SEARCHING STRINGS• Finding a character or substring within given string

• First occurrence

• First occurrence starting at given position

• Last occurrence

• Last occurrence before given position

indexOf(String str)

indexOf(String str, int fromIndex)

lastIndexOf(String)

lastIndexOf(String, int fromIndex)

Page 27: String and string manipulation x

SEARCHING STRINGS – EXAMPLE

String str = "Java Programming Course";

int index = str.indexOf("Java"); // index = 0

index = str.indexOf("Course"); // index = 17

index = str.indexOf("COURSE"); // index = -1

// indexOf is case sensetive. -1 means not found

index = str.indexOf("ram"); // index = 9

index = str.indexOf("r"); // index = 6

index = str.indexOf("r", 7); // index = 9

index = str.indexOf("r", 10); // index = 20

0 1 2 3 4 5 6 7 8 9 10 11 12 …

J a v a P r o g r a m m …

i =

s.charAt(i) =

Page 28: String and string manipulation x

SEARCHING STRINGSLive Demo

Page 29: String and string manipulation x

EXTRACTING SUBSTRINGS

• Extracting substrings

• str.substring(int beginIndex, int endIndex)

• lastIndex is not included

• str.substring(int beginIndex)

String filename = "C:\\Pics\\Rila2005.jpg";

String name = filename.substring(8, 16);

// name is Rila2005

String filename = "C:\\Pics\\Summer2005.jpg";

String nameAndExtension = filename.substring(8);

// nameAndExtension is Rila2005.jpg

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

C : \\ P i c s \\ R i l a 2 0 0 5 . j p g

Page 30: String and string manipulation x

EXTRACTING SUBSTRINGSLive Demo

Page 31: String and string manipulation x

SPLITTING STRINGS

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

• String regex – String with special format

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

String[] split(String regex)

String[] parts = "Ivan; Petar,Gosho".split("[;,]");

// this wil separate the stirng into three parts

// "Ivan", " Petar" and "Gosho"

Page 32: String and string manipulation x

SPLITTING STRINGS - EXAMPLE

String listOfBeers =

"Amstel, Zagorka, Tuborg, Becks.";

String[] beers = listOfBeers.split("[ ,.]");

System.out.println("Available beers are:");

for (String beer : beers) {

if (!"".equalsIgnoreCase(beer)) {

System.out.println(beer);

}

}

Page 33: String and string manipulation x

SPLITTING STRINGSLive Demo

Page 34: String and string manipulation x

OTHER STRING OPERATIONSReplacing Substrings, Changing Character Casing, Trimming

Page 35: String and string manipulation x

REPLACING SUBSTRINGS

• replace(String, String) – replaces all occurrences of given string with another

• The result is new string (strings are immutable)

String cocktail = "Vodka + Martini + Cherry";

String replaced = cocktail.replace("+", "and");

// Vodka and Martini and Cherry

Page 36: String and string manipulation x

CHANGING CHARACTER CASING

• Using method toLowerCase()

• Using method toUpperCase()

String alpha = "aBcDeFg";

String lowerAlpha = alpha.toLowerCase(); // abcdefg

System.out.println(lowerAlpha);

String alpha = "aBcDeFg";

String upperAlpha = alpha.toUpperCase(); // ABCDEFG

System.out.println(upperAlpha);

Page 37: String and string manipulation x

TRIMMING WHITE SPACE

• Using method trim()

String s = " example of white space ";

String clean = s.trim();

System.out.println(clean);

Page 38: String and string manipulation x

OTHER STRING OPERATIONSLive Demo

Page 39: String and string manipulation x

BUILDING AND MODIFYING STRINGS

Using StringBuilder Class

Page 40: String and string manipulation x

CONSTRUCTING STRINGS

• Strings are immutable

• concat(), replace(), trim(), ... return new string, do not modify the old one

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

• It runs very inefficiently!

public static string dupChar(char ch, int count){

String result = "";

for (int i=0; i<count; i++)

result += ch;

return result;

} Bad practice.

Avoid this!

Page 41: String and string manipulation x

CHANGING THE CONTENTS OF A STRING – STRINGBUILDER

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

• Use StringBuilder if you need to keep adding characters to a string

public static String reverseIt(String s) {

StringBuilder sb = new StringBuilder();

for (int i = s.length()-1; i >= 0; i--)

sb.append(s.charAt(i));

return sb.ToString();

}

Page 42: String and string manipulation x

THE STRINGBUILDER CLASS

• StringBuilder keeps a buffer memory, allocated in advance

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

H e l l o , J a v a !StringBuilder:

length() = 11

capacity() = 15 used buffer

(length())

unused

buffer

Capacity

Page 43: String and string manipulation x

THE STRINGBUILDER CLASS (2)

• StringBuilder(int capacity) constructor allocates in advance buffer memory of a given size

• By default 16 characters are allocated

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

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

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

Page 44: String and string manipulation x

THE STRINGBUILDER CLASS (3)

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

• delete(int start, int end) removes the characters in given range

• insert(int offset, String str) inserts given string (or object) at

given position

• replace(int start, int end, String str) replaces all

occurrences of a substring with given string

• toString() converts the StringBuilder to String object

Page 45: String and string manipulation x

STRINGBUILDER – EXAMPLE

• Extracting all capital letters from a string

public static String extractCapitals(String s) {

StringBuilder result = new StringBuilder();

for (int i = 0; i < s.length(); i++) {

char ch = s.charAt(i);

if (Character.isUpperCase(ch)) {

result.append(ch);

}

}

return result.toString();

}

Page 46: String and string manipulation x

HOW THE + OPERATOR DOES STRING

CONCATENATIONS?

• Consider following string concatenation:

• It is equivalent to this code:

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

• What happens when using + in a loop?

String result = str1 + str2;

StringBuffer sb = new StringBuffer();

sb.append(str1);

sb.append(str2);

String result = sb.toString();

Page 47: String and string manipulation x

USING STRINGBUILDERLive Demo

Page 48: String and string manipulation x

FORMATTING STRINGSUsing toString() and String.format()

Page 49: String and string manipulation x

METHOD TOSTRING()

• All classes have this public virtual method

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

• Most Java Platform types have own implementation of toString()

Page 50: String and string manipulation x

METHOD STRING.FORMAT()

• Applies templates for formatting strings

• Placeholders are used for dynamic text

• Like System.out.printf(…)

String template = "If I were %s, I would %s.";

String sentence1 = String.format(

template, "developer", "know Java");

System.out.println(sentence1);

// If I were developer, I would know Java.

String sentence2 = String.format(

template, "elephant", "weigh 4500 kg");

System.out.println(sentence2);

// If I were elephant, I would weigh 4500 kg.

Page 51: String and string manipulation x

FORMATTING DATES

• When we print Dates we use prefix t or T

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

• m – month

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

• H, M, S – hour, minute, second

Date now = (new GregorianCalendar()).getTime();

System.out.printf("Now is " +

"%1$td.%1$tm.%1$tY %1$tH:%1$tM:%1$tS", now);

// Now is 23.05.2006 21:09:32

Page 52: String and string manipulation x

FORMATTING STRINGSLive Demo

Page 53: String and string manipulation x

EXERCISES

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

"sample" "elpmas".

Write a program to check if in a given expression the brackets are put correctly.

Example of correct expression: ((a+b)/5-d). Example of incorrect expression: )(a+b)).

Page 54: String and string manipulation x

Write a program that finds how many times a substring is contained in a given text (perform

case insensitive search).

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

The result is: 9.

We are living in a yellow submarine. We don't

have anything else. Inside the submarine is

very tight. So we are drinking all the day.

We will move out of it in 5 days.

Page 55: String and string manipulation x

You are given a text. Write a program that changes the text in all regions identified by the

tags <upcase> and </upcase> to uppercase. The tags cannot be nested. Example:

The expected result:

We are living in a <upcase>yellow

submarine</upcase>. We don't have

<upcase>anything</upcase> else.

We are living in a YELLOW SUBMARINE. We don't

have ANYTHING else.

Page 56: String and string manipulation x

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

and extracts from it the [protocol], [server] and [resource] elements. For example from

the URL http://www.devbg.org/forum/index.php following information should be

extracted: [protocol] = "http", [server] = "www.devbg.org", [resource] =

"/forum/index.php"

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

Page 57: String and string manipulation x

Write a program that extracts from a given text all the sentences that contain given word.

Example: The word is "in". The text is:

The expected result is:

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

We are living in a yellow submarine. We don't

have anything else. Inside the submarine is

very tight. So we are drinking all the day.

We will move out of it in 5 days.

We are living in a yellow submarine.

We will move out of it in 5 days.

Page 58: String and string manipulation x

We are given a string containing a list of forbidden words and a text containing some of

these words. Write a program that replaces the forbidden words with asterisks. Example:

Words: "Java, JVM, Microsoft"

The expected result:

Microsoft announced its next generation Java

compiler today. It uses advanced parser and

special optimizer for the Microsoft JVM.

********* announced its next generation ****

compiler today. It uses advanced parser and

special optimizer for the ********* ***.

Page 59: String and string manipulation x

Write a program that reads a string from the console and lists all the different letters in the

string along with information how many times each letter is found.

Write a program that reads a string from the console and lists all the different words in the

string with information how many times each word is found.

Write a program that reads a string from the console and replaces all series of consecutive

identical letters with a single one. Example: "aaaaabbbbbcdddeeeedssaa" -> "abcdedsa".

Page 60: String and string manipulation x

Write a program that reads a list of words, separated by spaces (' ') , and prints the

list in an alphabetical order.

Write a program that lets the user input a string of maximum 20 characters. If the

length of the string is less, the rest of the characters should be filled with '*'. Print the

string into the console.