Eng. Mohammed Abdualal

Similar documents
Computer Programming, I. Laboratory Manual. Experiment #5. Strings & Text Files Input

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

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

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

Chapter 4 Mathematical Functions, Characters, and Strings

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

Module 4: Characters, Strings, and Mathematical Functions

Chapter 12 Strings and Characters. Dr. Hikmat Jaber

Chapter 4 Mathematical Functions, Characters, and Strings

Computer Programming, I. Laboratory Manual. Experiment #4. Mathematical Functions & Characters

String is one of mostly used Object in Java. And this is the reason why String has unique handling in Java(String Pool). The String class represents

Eng. Mohammed Abdualal

CHAPTER 4 MATHEMATICAL FUNCTIONS, CHARACTERS, STRINGS

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

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

Chapter 8 Strings. Chapter 8 Strings

Chapter 11 Object-Oriented Design Exception and binary I/O can be covered after Chapter 9

Chapter 4. Mathematical Functions, Characters, and Strings

Eng. Mohammed S. Abdualal

Chapter 9 Strings and Text I/O

CST242 Strings and Characters Page 1

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

Chapter 2 ELEMENTARY PROGRAMMING

Chapter 2 Primitive Data Types and Operations

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

Java Strings. Interned Strings. Strings Are Immutable. Variable declaration as String Object. Slide Set 9: Java Strings and Files

Programming with Java

Chapter 2 Primitive Data Types and Operations

Java Basic Datatypees

Strings, characters and character literals

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

Computer Programming, I. Laboratory Manual. Experiment #6. Loops

CS-201 Introduction to Programming with Java

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

Visual C# Instructor s Manual Table of Contents

STUDENT LESSON A10 The String Class

Loops. Eng. Mohammed Abdualal. Islamic University of Gaza. Faculty of Engineering. Computer Engineering Department

Chapter 2 Elementary Programming

Basic Computation. Chapter 2

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

Welcome to the Using Objects lab!

Getting started with Java

Variables, Constants, and Data Types

Full file at

Chapter 2 Primitive Data Types and Operations. Objectives

Tools : The Java Compiler. The Java Interpreter. The Java Debugger

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

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

Reading Input from Text File

CS 1301 Ch 8, Part A

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

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

3 The Building Blocks: Data Types, Literals, and Variables

Slide 1 CS 170 Java Programming 1 More on Strings Duration: 00:00:47 Advance mode: Auto

Strings in Java String Methods. The only operator that can be applied to String objects is concatenation (+) for combining one or more strings.

Lesson 02 Data Types and Statements. MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

4 Programming Fundamentals. Introduction to Programming 1 1

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

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

More on variables and methods

OOP-Lecture Java Loop Controls: 1 Lecturer: Hawraa Sh. You can use one of the following three loops: while Loop do...while Loop for Loop

Creating Strings. String Length

JAVA Programming Concepts

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

Basic Computation. Chapter 2

Java characters Lecture 8

Full file at

Chapter 10: Creating and Modifying Text Lists Modules

AP Computer Science A

10/9/2012. Computers are machines that process data. assignment in C# Primitive Data Types. Creating and Running Your First C# Program

String related classes

Overview of C. Basic Data Types Constants Variables Identifiers Keywords Basic I/O

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

Chapter 2: Data and Expressions

Java Foundations: Unit 3. Parts of a Java Program

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

What methods does the String class provide for ignoring case sensitive situations?

Elementary Programming

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

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Chapter 2: Data and Expressions

char ch = astring; //where astring is a String..illegal char ch = A ; //illegal

Language Fundamentals Summary

Basics of Java Programming

Java Notes. 10th ICSE. Saravanan Ganesh

Java: Learning to Program with Robots

Chapter 2: Using Data

DECLARATIONS. Character Set, Keywords, Identifiers, Constants, Variables. Designed by Parul Khurana, LIECA.

PYTHON- AN INNOVATION

Chapter 2: Data and Expressions

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

JAVASCRIPT BASICS. JavaScript String Functions. Here is the basic condition you have to follow. If you start a string with

Java Overview An introduction to the Java Programming Language

Strings. Upsorn Praphamontripong. Note: for reference when we practice loop. We ll discuss Strings in detail after Spring break

6.096 Introduction to C++ January (IAP) 2009

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

The Irving K. Barber School of Arts and Sciences COSC 111 Final Exam Winter Term II Instructor: Dr. Bowen Hui. Tuesday, April 19, 2016

CS Programming I: Using Objects

Transcription:

Islamic University of Gaza Faculty of Engineering Computer Engineering Department Computer Programming Lab (ECOM 2114) Created by Eng: Mohammed Alokshiya Modified by Eng: Mohammed Abdualal Lab 4 Characters & Strings Eng. Mohammed Abdualal October 10, 2015

Character Data Type and Operations The character data type, char, is used to represent a single character. A character literal is enclosed in single quotation marks. Example: char letter = 'A'; char numchar = '5'; In Java, char values represent Unicode characters. Unicode is a 16-bit character encoding that supports the world's major languages. You can indicate a Unicode character using \uxxxx escape sequence. Each X in the escape sequence is a hexadecimal digit. As example, character A can be represented in other way using Unicode encoding: char letter = '\u0041'; // Character A's Unicode is 0041 The following table representing Unicode values for commonly used characters: Characters Code Value in Decimal Unicode Value '0' to '9' 48 to 57 \u0030 to \u0039 'A' to 'Z' 65 to 90 \u0041 to \u005a 'a' to 'z' 97 to 122 \u0061 to \u007a Escape Sequences for Special Characters Java uses an escape sequence to represent special characters, which consists of a backslash (\) followed by a character or a combination of digits. For example, \t is an escape sequence for Tab character. The symbols in an escape sequence are interpreted as a whole rather than individually. An escape sequence is considered as a single character. 2

The following table lists escape sequences for special characters in java: Escape Sequence Name Unicode Code \b Backspace \u0008 \t Tab \u0009 \n Linefeed \u000a \f Formfeed \u000c \r Carriage Return \u000d \\ Backslash \u005c \ Double Quote \u0022 \ Single Quote \u0027 Task 1 Write ONE Java Statement to print to following lines to the Console: Welcom to "Java" Lab#4: Strings & Loops Casting between char and Numeric Types A char can be cast into a numeric type, for example, int or byte. When a char is cast into a numeric type, the character s Unicode is cast into the specified numeric type. Example: int i = (int) 'A'; // The Unicode of character A is assigned to i System.out.println(i); // i is 65 Implicit casting can be used if the result of a casting fits into the target variable. For example, since the Unicode of 'A' is 65, which is within the range of int, these implicit castings are fine: int i = 'A'; // i is 65 char c = 65; // c is 'A' 3

Note that all numeric operators can be applied to char operands. A char operand is automatically cast into a number if the other operand is a number or a character. If the other operand is a string, the character is concatenated with the string. For example, the following statements " int i = '2' + '3'; // (int)'2' is 50 and (int)'3' is 51 System.out.println("i is " + i); // i is 101 int j = 2 + 'a'; // (int)'a' is 97 System.out.println("j is " + j); // j is 99 System.out.println(j + " is the Unicode for character + (char)j); // 99 is the Unicode for character c System.out.println("Chapter " + '2'); display i is 101 j is 99 99 is the Unicode for character c Chapter 2 Task 2 Try to discover the Unicode code for numbers chars: 0, 1, 2,, 9. Comparting and Testing Characters You can use the same numeric comparison operators for comparing characters. Hence, 'a' < 'b' is true because the Unicode for 'a' (97) is less than the Unicode for 'b' (98). However, Java provides some static methods in Character class for comparing and converting characters. The following table lists some of those useful methods: Method isdigit(ch) isletter(ch) isletterordigit(ch) islowercase(ch) Description Returns true if the specified character is a digit. Returns true if the specified character is a letter. Returns true if the specified character is a letter or digit Returns true if the specified character is a lowercase letter. 4

isuppercase(ch) tolowercase(ch) touppercase(ch) Returns true if the specified character is an uppercase letter. Returns the lowercase of the specified character. Returns the uppercase of the specified character. Example: Write a program that receives a character, and check if it is a digit or letter. If digit, print its Unicode code. If letter, print its toggle case. Else, print not a digit nor a letter. FindTheUnicodeOfACharacter.java String s = JOptionPane.showInputDialog("Enter a character"); // Get the first character of a line char c = s.charat(0); if (Character.isDigit(c)) { // Character implicitly converted into int System.out.println(c + 0); } else if (Character.isUpperCase(c)) { System.out.println(Character.toLowerCase(c)); } else if (Character.isLowerCase(c)) { System.out.println(Character.toUpperCase(c)); } else { System.out.println("Not a digit nor a letter"); } 5

The String Type A string is a sequence of characters. To represent a string of characters, use the data type called String. A sequence of characters are enclosed in double quotation marks. Example: String str = "Hello World"; String is a predefined class in the Java library. It contains many useful methods manipulating characters. The following table lists the String methods for obtaining string length, for accessing characters in the string, for converting a string to upper or lowercases, and for trimming a string. Method Description length() Returns the number of characters in this string. charat(index) Returns the character at the specified index from this 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 trimmed on both sides. Getting Characters from a String The str.charat(index) method can be used to retrieve a specific character in a string str, where the index is between 0 and str.length() 1. For example, message.charat(0) returns the character W, as shown in the next figure. Note that the index for the first character in the string is 0. 6

Caution Attempting to access characters in a string str out of bounds is a common programming error. To avoid it, make sure that you do not use an index beyond str.length() 1. Example: Write a Java program to prompt the user to enter a line and output the following: How many characters in the line? The fifth character (if exists) All characters in uppercase All characters in lowercase Manipulating String String str = JOptionPane.showInputDialog("Enter a line"); // Remove white spaces from both sides str = str.trim(); // Count characters int length = str.length(); System.out.println("Length is: " + length); // Get the fifth character if (length >= 5) System.out.println("Fifth character is: " + str.charat(4)); else System.out.println("The fifth character does not exist"); System.out.println("Uppercase: " + str.touppercase()); System.out.println("Lowercase: " + str.tolowercase()); Comparing Strings Method Description equals(s1) Returns true if this string is equal to string s1. equalsignorecase(s1) Returns true if this string is equal to string s1; it is case insensitive. compareto(s1) Returns an integer greater than 0, equal to 0, or less than 0 to indicate whether this string is greater than, equal to, or less than s1. comparetoignorecase(s1) Same as compareto except that the comparison is case insensitive. startswith(prefix) Returns true if this string starts with the specified prefix. endswith(suffix) Returns true if this string ends with the specified suffix. contains(s1) Returns true if s1 is a substring in this string. 7

Obtaining Substrings You can obtain a substring from a string using the substring method. For example: String message = "Welcome to Java"; String message = message.sustring(0, 11)+"HTML"; The string message now becomes "Welcome to HTML". Note that the last character (11) is excluded. Finding a Character or a Substring in a String The String class provides several versions of indexof and lastindexof methods to find a character or a substring in a string, as shown in the following table: Method indexof(ch) indexof(ch, fromindex) indexof(s) indexof(s, fromindex) lastindexof(ch) lastindexof(ch, fromindex) Description Returns the index of the first occurrence of ch in the string. Returns the index of the first occurrence of ch after fromindex in the string. Returns the index of the first occurrence of string s in this string. Returns the index of the first occurrence of string s in this string after fromindex. Returns the index of the last occurrence of ch in the string. Returns the index of the last occurrence of ch before fromindex in this string. 8

lastindexof(s) Returns the index of the last occurrence of string s. lastindexof(s, fromindex) Returns the index of the last occurrence of string s before fromindex. Note that all the previous methods return (-1) if not matched. Examples: 11 "Welcome to Java".indexOf('W') returns 0 "Welcome to Java".indexOf('o') returns 4 "Welcome to Java".indexOf('o', 5) returns 9 "Welcome to Java".indexOf("come") returns 3 "Welcome to Java".indexOf("Java", 5) returns 11 "Welcome to Java".indexOf("java", 5) returns -1 "Welcome to Java".lastIndexOf('W') returns 0 "Welcome to Java".lastIndexOf('o') returns 9 "Welcome to Java".lastIndexOf('o', 5) returns 4 "Welcome to Java".lastIndexOf("come") returns 3 "Welcome to Java".lastIndexOf("Java") returns Example: Write a Java program to prompt the user to enter his full name as FirstName LastName, and the program prints each word in a line. Solution String s = JOptionPane.showInputDialog("Enter Full Name"); int sp = s.indexof(" "); String firstname = s.substring(0, sp); String lastname = s.substring(sp + 1); System.out.println("First Name is: " + firstname); System.out.println("Last Name is: " + lastname); Note that there is a better solution for the previous example, using StringTokenizer class, which can be used as follow: Solution using StringTokenizer String s = JOptionPane.showInputDialog("Enter Full Name"); StringTokenizer st = new StringTokenizer(s, " "); String token; while (st.hasmoretokens()) { token = st.nexttoken(); System.out.println(token); } 9

10

Exercises: Part 1: Write a program that prompts the user to enter a character c and check which character is entered: If 'U', then generate a random uppercase letter. If 'L', then generate a random lowercase letter. Your program should ignore the case of the character (uppercase = lowercase). Else, print: (Your character\ "o"). replace o with the input character. Sample Input U L X Sample Output Randomly generated uppercase letter is: "M" Randomly generated uppercase letter is: "g" Your character\ "x" Hint: to generate a random number r in range a <= r <= b, use the formula: int r = (int)(math.random() * (b a + 1) + a); Part 2: (Evaluate simple expression) Write a program to prompt the user to enter a simple equation with one operator (*, /, +, -, %), and two operands (decimal numbers) (Ex. 5 * 6.3 ), and output the result of the expression. Note that there can be more than one white space between operator and operands. Example: 11

Part 3: (English words without vowels) Write a program that reads an English word and check if it contains vowels (a, e, i, o, u). If so, output Contains vowels, else, output No vowels found. Sample Input Sample Output Java Contains vowels Sky No vowels found Hint: to delete a specific character from a string, then replace it with an empty string(""). Example: String s = "Hello World"; S = s.replaceall("rl", ""); As a result: S = "Hello Wod"; 12