Strings. Strings and their methods. Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

Similar documents
Strings. Strings and their methods. Mairead Meagher Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

More on Strings. String methods and equality. Mairead Meagher Dr. Siobhán Drohan. Produced by: Department of Compu<ng and Mathema<cs h=p://

STUDENT LESSON A10 The String Class

Creating Strings. String Length

Using Java Classes Fall 2018 Margaret Reid-Miller

Strings. Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

"Hello" " This " + "is String " + "concatenation"

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Appendix 3. Description: Syntax: Parameters: Return Value: Example: Java - String charat() Method

Programming with Java

We now start exploring some key elements of the Java programming language and ways of performing I/O

Java Basic Datatypees

A variable is a name for a location in memory A variable must be declared

More on variables and methods

CS1150 Principles of Computer Science Math Functions, Characters and Strings (Part II)

appreciate the difference between a char and a string understand and use the String class methods

An Introduction to Processing

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing

STRINGS AND STRINGBUILDERS. Spring 2019

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

Java s String Class. in simplest form, just quoted text. used as parameters to. "This is a string" "So is this" "hi"

MATHEMATICAL FUNCTIONS CHARACTERS, AND STRINGS. INTRODUCTION IB DP Computer science Standard Level ICS3U

Intro to Strings. Lecture 7 CGS 3416 Spring February 13, Lecture 7 CGS 3416 Spring 2017 Intro to Strings February 13, / 16

Getting started with Java

Eng. Mohammed Abdualal

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

Full file at

Intro to Strings. Lecture 7 COP 3252 Summer May 23, 2017

Activity 9: Object-Oriented

AP Computer Science A

CMPT 125: Lecture 3 Data and Expressions

Key Differences Between Python and Java

Language Reference Manual

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

Chapter 1 Introduction to java

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

Lecture Set 2: Starting Java

Lecture Set 2: Starting Java

CSC 1051 Algorithms and Data Structures I. Midterm Examination March 1, Name: KEY A

CHAPTER 4 MATHEMATICAL FUNCTIONS, CHARACTERS, STRINGS

Activity 9: Object-Oriented

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

4 Programming Fundamentals. Introduction to Programming 1 1

More non-primitive types Lesson 06

Strings, Strings and characters, String class methods. JAVA Standard Edition

Comments in a Java Program. Java Overview. Identifiers. Identifier Conventions. Primitive Data Types and Declaring Variables

Visual C# Instructor s Manual Table of Contents

Lab 14 & 15: String Handling

CS 106 Introduction to Computer Science I

Eng. Mohammed Abdualal

Strings! Today! CSE String Methods!

The Java Language Rules And Tools 3

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

Review. Single Pixel Filters. Spatial Filters. Image Processing Applications. Thresholding Posterize Histogram Equalization Negative Sepia Grayscale

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Computational Expression

AP Computer Science. Strings. Credit: Slides are modified with permission from Barry Wittman at Elizabethtown College

Ticket Machine Project(s)

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

Java Foundations: Unit 3. Parts of a Java Program

Variables, Constants, and Data Types

Programming: Java. Chapter Objectives. Control Structures. Chapter 4: Control Structures I. Program Design Including Data Structures

Java characters Lecture 8

Chapter 29: String and Object References Bradley Kjell (Revised 06/15/2008)

USING LIBRARY CLASSES

CST242 Strings and Characters Page 1

CSE1710. Big Picture. Tuesday, Dec 02 is designated as a study day. No classes. Thursday, Dec 04 is last lecture.

Java Fall 2018 Margaret Reid-Miller

COMP6700/2140 Data and Types

TCL - STRINGS. Boolean value can be represented as 1, yes or true for true and 0, no, or false for false.

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University

Mathematical Functions, Characters, and Strings. CSE 114, Computer Science 1 Stony Brook University

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

- Thus there is a String class (a large class)

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 11, Name: KEY

Professor: Sana Odeh Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators

CSC 1051 Algorithms and Data Structures I. Midterm Examination March 2, Name:

Language Reference Manual

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Chapter 4 Mathematical Functions, Characters, and Strings

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 6, Name:

Chapter 10: Creating and Modifying Text Lists Modules

Fall 2017 CISC124 9/16/2017

Fundamentals of Programming. By Budditha Hettige

String related classes

Honors Computer Programming 1-2. Chapter 5 Exam Prep

CS112 Lecture: Characters and Strings

Classes and Objects Part 1

Java Bytecode (binary file)

Programming with Java

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

B.V. Patel Institute of BMC & IT, UTU 2014

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Gaddis: Starting Out with Java: From Control Structures through Objects, 6/e

Decisions in Java IF Statements

CS1004: Intro to CS in Java, Spring 2005

Chapter 2 Part 2 Edited by JJ Shepherd, James O Reilly

Transcription:

Strings Strings and their methods Produced by: Dr. Siobhán Drohan Department of Computing and Mathematics http://www.wit.ie/

Topics list Primitive Types: char Object Types: String Primitive vs Object Types Strings and Java API Method calls (internal, external, dot notation) Escape Sequences Strings and methods: charat substring length touppercase tolowercase trim compareto equals

Primitive Types Java programming language supports eight primitive data types. The char data type stores one single character which is delimited by single quotes( ) e.g. char letter = a ; Data Type Default Value byte 0 short 0 int 0 long 0L float 0.0f double 0.0d char '\u0000' boolean false

Primitive Types: char // VALID USE char letter = n ; char letter = N ; //Assign n to the letter variable //Assign N to the letter variable // INVALID USE char letter = n; //ERROR no single quotes around n. char letter = n ; //ERROR double quotes around n. char letter = not ; //ERROR char can only hold one character. Source: Reas & Fry (2014)

Primitive Types: char char is a 16-bit Unicode character. Values range: from '\u0000 (or 0) to '\uffff' (or 65,535) For example: A is \u0041 a is \u0061 http://en.wikipedia.org/wiki/list_of_unicode_characters

Topics list Primitive Types: char Object Types: String Primitive vs Object Types Strings and Java API Method calls (internal, external, dot notation) Escape Sequences Strings and methods: charat substring length touppercase tolowercase trim compareto equals

Object types e.g. String Strings, which are widely used in Java, are a sequence of characters enclosed by double quotes ( ). In Java, a String is an object type. The Java platform provides the String class to create and manipulate strings. The most direct way to create a String is to write: String greeting = "Hello world!"; http://www.tutorialspoint.com/java/pdf/java_strings.pdf

Object types - String // VALID USE String str = I am a sentence ; //Assigns the full sentence to str variable. String word = dog ; //Assigns the word dog to the word variable. String letter = A ; //Assigns the letter A to the letter variable. // INVALID USE String letter = n; //ERROR no double quotes around n. String letter = n ; //ERROR single quotes around n; use double. string letter = n ; //ERROR String should have a capital S. Source: Reas & Fry (2014)

Topics list Primitive Types: char Object Types: String Primitive vs Object Types Strings and Java API Method calls (internal, external, dot notation) Escape Sequences Strings and methods: charat substring length touppercase tolowercase trim compareto equals

Primitive vs. Object Types Primitive type int i; 17 With primitive type variables (e.g. int, float, char, etc) the value of the variable is stored in the memory location assigned to the variable.

Primitive vs. Object Types String greeting; Hello World! With object types, the variable holds the memory address of where the object is located it does not store the values inside the object. This memory address is called a reference to the object.

Primitive vs. Object Types String greeting; String is an object type. int i; 17 primitive type Hello World! The greeting variable contains a reference to where the String is stored in memory.

Primitive vs. Object Types String a; String b; Hello World! b = a; int a; 17 int b; 17

Topics list Primitive Types: char Object Types: String Primitive vs Object Types Strings and Java API Method calls (internal, external, dot notation) Escape Sequences Strings and methods: charat substring length touppercase tolowercase trim compareto equals

https://docs.oracle.com/javase/tutorial/java/data/manipstrings.html Strings: index of characters A String holds a sequence of characters. The index of the first character in a String is 0. The index of the last character in a String is length()-1.

Strings are objects Variables created with the String data type are called objects. Objects are software structures that combine variables with methods that operate on those variables e.g. every String object has a built-in method that can capitalise its letters.

Strings and Java s API This link is to Java s Application Programming Interface (API). https://docs.oracle.com/javase/8/docs/api/index.html?o verview-summary.html At the moment, we are interested in finding out more information on String, particularly its methods: https://docs.oracle.com/javase/8/docs/api/java/lang/str ing.html

Topics list Primitive Types: char Object Types: String Primitive vs Object Types Strings and Java API Method calls (internal, external, dot notation) Escape Sequences Strings and methods: charat substring length touppercase tolowercase trim compareto equals

External method calls Say we want to check the length of this String: String name = Joe Soap ; Looking at the String API, we can see this method: ReturnType Method Description int length() Returns the length of this string. A call to a method of another object is called an external method call.

External method calls External method calls have the syntax: object.methodname ( parameter-list) To find out the length of this String: String name = Joe Soap ; We make the following external method call: name.length();

External method call

Dot Notation Methods can call methods of other objects using dot notation. This syntax is known as dot notation: object.methodname ( parameter-list) It consists of: An object A dot A method name The parameters for the method

Topics list Primitive Types: char Object Types: String Primitive vs Object Types Strings and Java API Method calls (internal, external, dot notation) Escape Sequences Strings and methods: charat substring length touppercase tolowercase trim compareto equals

Java Escape Sequences When a String is printed, certain single characters that follow a backslash (\) have special meaning and the compiler interprets them accordingly. http://docs.oracle.com/javase/tutorial/java/data/characters.html

Java Escape Sequences Escape Sequence Description \t Insert a tab in the text at this point. \b Insert a backspace in the text at this point. \n Insert a newline in the text at this point. \r Insert a carriage return in the text at this point. \f Insert a formfeed in the text at this point. \' Insert a single quote character in the text at this point. \" Insert a double quote character in the text at this point. \\ Insert a backslash character in the text at this point. http://docs.oracle.com/javase/tutorial/java/data/characters.html

Java Escape Sequences - examples System.out.print( Java\n ); is the exact same as: System.out.println( Java ); System.out.println( Java ); is similar to: System.out.println( \tjava ); http://docs.oracle.com/javase/tutorial/java/data/characters.html

Topics list Primitive Types: char Object Types: String Primitive vs Object Types Strings and Java API Method calls (internal, external, dot notation) Escape Sequences Strings and methods: charat substring length touppercase tolowercase trim compareto equals

Strings and some API methods Return Type Method Name Description char charat(int index) Returns the char value at the specified index. String substring(int beginindex, int endindex) Returns a string that is a substring of this string. int length() Returns the length of this string. String touppercase() Converts all of the characters in this String to upper case. String tolowercase() Converts all of the characters in this String to lower case. String trim() Returns a string whose value is this string, with any leading and trailing whitespace removed. int compareto(string anothers tring) Compares two strings lexicographically (i.e. unicode ordering). boolean equals (Object anobject) Compares this string to the specified object. https://docs.oracle.com/javase/8/docs/api/java/lang/string.html

Topics list Return type Method Description char charat(int index) Returns the char value at the specified index. Strings and methods: charat substring length touppercase tolowercase trim compareto equals

https://docs.oracle.com/javase/tutorial/java/data/manipstrings.html String methods: charat(int index) The following code gets the character at index 9 in a String: String anotherpalindrome = "Niagara. O roar again!"; char achar = anotherpalindrome.charat(9); Indices begin at 0, so the character at index 9 is 'O'

Finding the character located a specific position in a String.

Topics list Return type String Method substring(int beginindex, int endindex) Description Returns a string that is a substring of this string. Strings and methods: charat substring length touppercase tolowercase trim compareto equals

String methods: substring(int beginindex, int endindex) This method returns a new String that is a substring of this String. The substring begins at the specified beginindex and extends to the character at index endindex 1. String anotherpalindrome = "Niagara. O roar again!"; String roar = anotherpalindrome.substring(11, 15); This code returns a substring ( roar ) from anotherpalindrome. It extends from index 11 up to, but not including, index 15. https://docs.oracle.com/javase/tutorial/java/data/manipstrings.html

Printing out a substring of a String to the console.

Printing out a substring of a String to the console.

Topics list Return type int Method length() Description Returns the length of this string. Strings and methods: charat substring length touppercase tolowercase trim compareto equals

Printing the length of a String to the console.

Printing the length of a String to the console.

Topics list Return type String Method touppercase() Description Converts all of the characters in this String to upper case. Strings and methods: charat substring length touppercase tolowercase trim compareto equals

Converting a String to UPPERCASE and printing it to the console.

Topics list Return type String Method tolowercase() Description Converts all of the characters in this String to lower case. Strings and methods: charat substring length touppercase tolowercase trim compareto equals

Converting a String to lowercase and printing it to the console.

Topics list Return type String Method trim() Description Returns a string whose value is this string, with any leading and trailing whitespace removed. Strings and methods: charat substring length touppercase tolowercase trim compareto equals

Removing all the leading and trailing spaces in a String and printing it to the console.

Topics list Return type int Method compareto(string anotherstring) Description Compares two strings lexicographically (i.e. unicode ordering). Strings and methods: charat substring length touppercase tolowercase trim compareto equals

String methods: compareto int compareto (String anotherstring) This method compares two strings lexicographically i.e. based on the Unicode value of the characters in the String. It returns an integer indicating whether this string is: greater than (result is > 0) equal to (result is = 0) or less than (result is < 0) the argument, anotherstring. https://docs.oracle.com/javase/tutorial/java/data/comparestrings.html

compareto: Example 1 String str1 = "Dog"; String str2 = "Cat"; What will be printed to the console? Which boolean expression evaluates to true? if(str1.compareto(str2) < 0){ System.out.println(str1+" comes before "+ str2 +" in the alphabet"); else if(str1.compareto(str2) > 0){ System.out.println(str2 +" comes before "+ str1+" in the alphabet"); else{ System.out.println("The strings are identical");

compareto: Example 1 String str1 = "Dog"; String str2 = "Cat"; str1.compareto(str2) returns a positive integer as Dog (str1) comes after Cat (str2). if(str1.compareto(str2) < 0){ System.out.println(str1+" comes before "+ str2 +" in the alphabet"); else if(str1.compareto(str2) > 0){ System.out.println(str2 +" comes before "+ str1+" in the alphabet"); else{ System.out.println("The strings are identical");

compareto: Example 2 String str1 = cat"; String str2 = "Cat"; What What will be will printed be printed to the to console? the console? Which boolean expression evaluates to true? if(str1.compareto(str2) < 0){ System.out.println(str1+" comes before "+ str2 +" in the alphabet"); else if(str1.compareto(str2) > 0){ System.out.println(str2 +" comes before "+ str1+" in the alphabet"); else{ System.out.println("The strings are identical");

compareto: Example 2 String str1 = cat"; String str2 = "Cat"; str1.compareto(str2) What will be printed returns to a positive integer the console? as cat (str1) comes after Cat (str2) in the Unicode character map. if(str1.compareto(str2) < 0){ System.out.println(str1+" comes before "+ str2 +" in the alphabet"); else if(str1.compareto(str2) > 0){ System.out.println(str2 +" comes before "+ str1+" in the alphabet"); else{ System.out.println("The strings are identical");

compareto: Example 3 String str1 = "Animal"; String str2 = "Cat"; What What will be will printed be printed to the to console? the console? Which boolean expression evaluates to true? if(str1.compareto(str2) < 0){ System.out.println(str1+" comes before "+ str2 +" in the alphabet"); else if(str1.compareto(str2) > 0){ System.out.println(str2 +" comes before "+ str1+" in the alphabet"); else{ System.out.println("The strings are identical");

compareto: Example 3 String str1 = "Animal"; String str2 = "Cat"; str1.compareto(str2) returns a negative integer as Animal(str1) comes before Cat (str2) in the Unicode character map. if(str1.compareto(str2) < 0){ System.out.println(str1+" comes before "+ str2 +" in the alphabet"); else if(str1.compareto(str2) > 0){ System.out.println(str2 +" comes before "+ str1+" in the alphabet"); else{ System.out.println("The strings are identical");

compareto: Example 4 String str1 = Cat"; String str2 = "Cat"; What will be printed to the console? Which boolean expression evaluates to true? if(str1.compareto(str2) < 0){ System.out.println(str1+" comes before "+ str2 +" in the alphabet"); else if(str1.compareto(str2) > 0){ System.out.println(str2 +" comes before "+ str1+" in the alphabet"); else{ System.out.println("The strings are identical");

compareto: Example 4 String str1 = Cat"; String str2 = "Cat"; str1.compareto(str2) returns 0 as Cat (str1) is identical to Cat (str2). if(str1.compareto(str2) < 0){ System.out.println(str1+" comes before "+ str2 +" in the alphabet"); else if(str1.compareto(str2) > 0){ System.out.println(str2 +" comes before "+ str1+" in the alphabet"); else{ System.out.println("The strings are identical");

Topics list Return type boolean Method equals (Object anobject) Description Compares this string to the specified object. Strings and methods: charat substring length touppercase tolowercase trim compareto equals

String: Identity vs Equality (1) if(input == "bye") {... tests identity i.e. the reference if(input.equals("bye")) {... tests equality Strings should always be compared using the.equals method

String: Identity vs Equality (2) String input = "bye"; if(input == "bye") {... == tests identity :String "bye" :String ==? "bye" input

String: Identity vs Equality (2) String input = "bye"; if(input == "bye") {... == tests identity :String "bye" == :String "bye" input (may be) false!

String: Identity vs Equality (3) String input = "bye"; if(input.equals("bye")) {... equals tests equality :String "bye" equals :String "bye"? input

String: Identity vs Equality (3) String input = "bye"; if(input.equals("bye")) {... equals tests equality :String "bye" equals :String "bye" input true!

Some common errors when comparing Strings...

What s wrong here? public void anymethod() { String str1 = "a"; String str2 = "b"; if(str1 == str2) { System.out.println(str1+" is the same as "+ str2); else { System.out.println(str1+" is NOT same as "+ str2);

Strings need to use the.equals method public void anymethod() { String str1 = "a"; String str2 = "b"; if(str1 == str2) { System.out.println(str1+" is the same as "+ str2); else { System.out.println(str1+" is NOT same as "+ str2);

What s wrong here? public void anymethod() { int num1 = 1; int num2 = 2; if(num1 = num2) { System.out.println(num1+" is the same as "+ num2); else { System.out.println(num1+" is NOT same as "+ num2);

You need two equals for equality public void anymethod() { int num1 = 1; int num2 = 2; if(num1 = num2) { System.out.println(num1+" is the same as "+ num2); else { System.out.println(num1+" is NOT same as "+ num2);

Questions?

References Reas, C. & Fry, B. (2014) Processing A Programming Handbook for Visual Designers and Artists, 2 nd Edition, MIT Press, London.

Department of Computing and Mathematics http://www.wit.ie/