0% found this document useful (0 votes)
3 views25 pages

04 Strings

This document about Java Strings

Uploaded by

adsad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views25 pages

04 Strings

This document about Java Strings

Uploaded by

adsad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Strings

BZ 214 Visual Programming

Asst. Prof. Dr. Ahmet Nusret Toprak

Erciyes University
Department of Computer Engineering

(BZ 214 Visual Programming) Strings 1 / 24


Objectives

To represent strings using the String objects


To program common String operations
To compare strings
String conversions
StringBuilder and StringBuffer classes

(BZ 214 Visual Programming) Strings 1 / 24


The String Type

The char type only represents one character.


To represent a string of characters, use the data type called String.
String message = " Welcome to Java " ;

String is actually a predefined class in the Java library


The String type is not a primitive type

(BZ 214 Visual Programming) Strings 2 / 24


Reading a String from the Console

You can read a string from console using Scanner class


Scanner input = new Scanner ( System . in );
String s1 = input . next ();
String s2 = input . nextLine ();

(BZ 214 Visual Programming) Strings 3 / 24


Basic Methods for String Objects

Strings are objects in Java.


The methods in the preceding table can only be invoked from a
specific string instance.
For this reason, these methods are called instance methods.

Method Description
length() returns the number of characters in a string
charAt(index) returns the character at the specified index from this string
concat(String) returns a new string that concantenate this string with argument string
toUpperCase() returns a new string with all letters in uppercase
toLowerCase() returns a new string with all letters in lowercase
trim() returns a new string with whitespace characters trimmeds

(BZ 214 Visual Programming) Strings 4 / 24


String Concatenation

The + operator is overloaded to mean concatenation for String objects.


Strings can be concatenated
String uni = " er " + " ci " + " yes " ; // Now uni is " erciyes "

Primitive types can also be concatenated with Strings.


String s = uni + 1; // s is " erciyes1 "

The concat() method concatenates the specified string to the end of


current string
String s1 = " Visual " ;
String s2 = " Programming " ;
String s3 = s1 . concat ( s2 ); // s3 is " Visual Programming "

(BZ 214 Visual Programming) Strings 5 / 24


Split Strings

The string split() method breaks a given string around matches of


the given regular expression
split() method takes a regular expression
// string . split ( regex , limit )

String string = " 004 -034556 " ;


String [] parts = string . split (" -" );
String part1 = parts [0]; // 004
String part2 = parts [1]; // 034556

(BZ 214 Visual Programming) Strings 6 / 24


Replacing Strings

replace (oldChar, newChar)


returns a new string that replaces all matching character with new
character
replaceFirst(oldString, newString)
returns a new string that replaces the first matching substring with
new substring
replaceAll(oldString, newString)
returns a new string that replaces all matching substring with new
substring
" erciyes ". replace ( ’e ’ , ’A ’ ); // ArciyAs
" erciyes ". replaceFirst ( " e " , " AB " ); // ABrciyes
" erciyes ". replaceAll ( " e " , " AB " ); // ABrciyABs

(BZ 214 Visual Programming) Strings 7 / 24


Comparing Strings

We can compare strings in Java on the basis of content using


following methods

Method Description
equals(String s1) returns true if this string equals to string s1
equalsIgnoreCase(String) returns true if this string equals to string s1 (it is case insensetive)
returns an integer greater than 0 if this string greater than s1
compareTo(String) returns 0 if this string equals to s1
returns an integer less than 0 if this string less than s1
compareToIgnoreCase(String) same as compareTo() except that comparison is case insensetive
startsWith(prefix) returns true if this string starts with specified prefix
endsWith(suffix) returns true if this string ends with specified postfix

Note: "==" operator only checks the referential equality of two Strings, meaning if
they reference the same object or not.

(BZ 214 Visual Programming) Strings 8 / 24


Obtaining Substrings

Method Description
returns this string’s substring that begins with the character
substring(beginIndex)
at the specified beginIndex and extends to the end of the string
returns this string’s subtrings that begins at the specified
substring(beginIndex, endIndex) beginIndex and extends to the character at index endIndex-1.
Note that the character at endIndex is not part of the substring

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

message J A V A P R O G R A M M I N G

message.substring(0, 10) message.substring(10)

(BZ 214 Visual Programming) Strings 9 / 24


Finding a Character or a Substring in a String

Method Description
returns index of the first occurence of ch in the string.
indexOf(char ch)
return -1 if not matched
returns index of the first occurence of ch after fromIndex in the string.
indexOf(ch, fromIndex)
return -1 if not matched
returns index of the first occurence of s in the string.
indexOf(String s)
return -1 if not matched
returns index of the first occurence of s after fromIndex in the string.
indexOf(s, fromIndex)
return -1 if not matched
returns index of the last occurence of ch in the string.
lastIndexOf(ch)
return -1 if not matched
returns index of the last occurence of ch before fromIndex in the string.
lastIndexOf(ch, fromIndex)
return -1 if not matched
returns index of the last occurence of s in the string.
lastIndexOf(s)
return -1 if not matched
returns index of the last occurence of s before fromIndex in the string.
lastIndexOf(s, fromIndex)
return -1 if not matched

(BZ 214 Visual Programming) Strings 10 / 24


Convert Character and Numbers to Strings

The String class provides several static valueOf() methods for


converting a character, an array of characters, and numeric values to
strings
These methods have the same name valueOf() with different
argument types char, char[], double, long, int, and float
String pi = String . valueOf (3.14);

(BZ 214 Visual Programming) Strings 11 / 24


Conversion between Strings and Numbers

You can use parsing methods of wrapper classes


String intString = " 12 " ;
String doubleString = " 15.5 " ;
int intValue = Integer . parseInt ( intString );
double doubleValue = Double . parseDouble ( doubleString );

Number to string:
I You can use toString() methods of Wrapper Classes (e.g. Integer)
I You can use static valueOf() method of String class
int value = 12;
String intString = Integer . toString ( value ); // "12"

String doubleString = String . valueOf (5.44); // "5.44"

(BZ 214 Visual Programming) Strings 12 / 24


Matching, Replacing and Splitting by Patterns

You can match, replace, or split a string by specifying a pattern


This is an extremely useful and powerful feature, commonly known as
regular expression
" Java " . matches (" Java " );
" Java " . equals (" Java " );

" Java is fun ". matches ( " Java .* " );


" Java is cool ". matches (" Java .* " );

(BZ 214 Visual Programming) Strings 13 / 24


Matching, Replacing and Splitting by Patterns

The replaceAll, replaceFirst, and split methods can be used


with a regular expression
For example, the following statement returns a new string that
replaces $, +, or # in "a+b$#c" by the string NNN
String s = "a+ b$ #c" . replaceAll ( "[ $ +#] " , " NNN " );
System . out . println ( s ); // displays : aNNNbNNNNNNc

The following statement splits the string into an array of strings


delimited by some punctuation marks
String [] tokens = " Java , C ?C # ,C ++ " . split (" [. ,:;?] " );
for ( int i = 0; i < tokens . length ; i ++)
System . out . println ( tokens [i ]); // displays : Java C C # C ++

(BZ 214 Visual Programming) Strings 14 / 24


Regular Expressions

A regular expression defines a search pattern for strings


The abbreviation for regular expression is regex
The search pattern can be anything from a simple character, a fixed
string or a complex expression containing special characters describing
the pattern.
Regular expressions can be used to search, edit and manipulate text.
Please see Appendix 2: Regular Expressions for detail.

(BZ 214 Visual Programming) Strings 15 / 24


Strings are Immutable

A String object is immutable; its contents cannot be changed


String s = " Java ";
s = " C ++ ";

After executing String s ="Java" After executing String s ="C++"

s s
:String :String This string object is
now unreferenced
String object for "Java" String object for "Java"

Contents cannot be
changed :String

String object for "C++"

(BZ 214 Visual Programming) Strings 16 / 24


Interned Strings

Since strings are immutable and are frequently used, to improve


efficiency and save memory, the JVM uses a unique instance for string
literals with the same character sequence
Such an instance is called interned
String s1 = " Welcome to Java " ;
String s2 = new String (" Welcome to Java " );
String s3 = " Welcome to Java " ;

System . out . println ( " s1 == s2 is " + ( s1 == s2 )); // false


System . out . println ( " s1 == s3 is " + ( s1 == s3 )); // true

s1 s2
:String :String
s3
Interned string object A string object for
for "Welcome to Java" "Welcome toJava"

(BZ 214 Visual Programming) Strings 17 / 24


StringBuilder and StringBuffer

The StringBuilder/StringBuffer class is an alternative to the String


class
In general, a StringBuilder/StringBuffer can be used wherever a string
is used
StringBuilder/StringBuffer is more flexible than String
You can add, insert, or append new contents into a string buffer,
whereas the value of a String object is fixed once the string is created

(BZ 214 Visual Programming) Strings 18 / 24


StringBuilder Class
StringBuilder class is mutable sequence of characters
StringBuilder objects are like String objects, except that they can be
modified.
They are treated like variable-length arrays that contain a sequence of
character
The length and content of the sequence can be changed through
method invocations.

(BZ 214 Visual Programming) Strings 19 / 24


StringBuilder Class

Method Description
StringBuilder append(aPrimitiveType v)
Appends the argument to this string builder
append(char[] str)
The data is converted to a string
StringBuilder append(char[] str, int offset, int len)
before the append operation takes place
StringBuilder append(String s)
StringBuilder delete(int start, int end) Deletes characters from start to end
StringBuilder deleteCharAt(int index) Deletes the character located at index
Replaces the characters from start to end in this string
StringBuilder replace(int start, int end, String s)
builder with the specified string
void setCharAt(int index, char c) Replaces the specified character in this string builder
StringBuilder insert(int offset, aPrimitiveType v) Inserts a value converted to String int to this builder
StringBuilder insert(int index, char[] str, Inserts a subarray of data in the array to the builder
int offset, int len) at the specified index
StringBuilder insert(int offset, char[] str) Inserts data into this builder at the position offset
StringBuilder insert(int offset, String s) Inserts string into this builder at the position offset
StringBuilder reverse() Reverses the sequence of characters in this string builder.

(BZ 214 Visual Programming) Strings 20 / 24


StringBuilder Class

Method Description
int capacity() Returns the capacity of this string builder
int length() Returns the number of characters of this string builder
void setLength(int newLength) Sets a new length in this builder
Returns a string that contains the character sequence
String toString()
in the builder
void trimToSize() Reduces the storage size used for string builder
String substring(int start) Returns a substring starting at start
String substring(int start, int end) Returns a substring from start to end -1

(BZ 214 Visual Programming) Strings 21 / 24


StringBuilder Examples

StringBuilder stringBuilder = new StringBuilder ( " Welcome to Java " );

stringBuilder . append ( " Java " ); // changes to " Welcome to Java Java "
stringBuilder . insert (11 , " HTML and " ); // " Welcome to HTML and Java "
stringBuilder . delete (8 , 11); // changes to " Welcome Java "
stringBuilder . deleteCharAt (8); // changes to " Welcome o Java "
stringBuilder . reverse (); // changes to " avaJ ot emocleW ".
stringBuilder . replace (11 , 15 , " HTML " ) // changes to " Welcome to HTML "
stringBuilder . setCharAt (0 , ’w ’) // sets to " welcome to Java "

(BZ 214 Visual Programming) Strings 22 / 24


StringBuffer Class

A thread-safe, mutable sequence of characters


A string buffer is like a String, but can be modified
It contains some particular sequence of characters, but the length and
content of the sequence can be changed through certain method calls
StringBuffer sb = new StringBuffer ( " Visual Programming " );
System . out . println ( sb . length ()); // displays 18
System . out . println ( sb . capacity ()); // displays 34

As of release JDK 5, this class has been supplemented with an


equivalent class designed for use by a single thread, StringBuilder.
Prefer The StringBuilder to this one, as it supports all of the same
operations but it is faster, as it performs no synchronization.

(BZ 214 Visual Programming) Strings 23 / 24


Case Study:

Problem
A palindrome is a word, number, phrase, or other sequence of characters
which reads the same backward as forward. Given a string, determine if it
is a palindrome, considering only alphanumeric characters and ignoring
cases. For example, A man, a plan, a canal: Panama is a palindrome.

Solution
Write methods to reverse the given string and filter the non-alphanumeric
characters. You can use equals() method to check if two strings are equal.

(BZ 214 Visual Programming) Strings 24 / 24

You might also like