Eng. Mohammed Abdualal

Similar documents
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.

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

Creating Strings. String Length

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

String related classes

Chapter 8 Strings. Chapter 8 Strings

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

Eng. Mohammed Abdualal

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

CS 1301 Ch 8, Part A

Chapter 10: Text Processing and More about Wrapper Classes

Lab 14 & 15: String Handling

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

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

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

CST242 Strings and Characters Page 1

Chapter 12 Strings and Characters. Dr. Hikmat Jaber

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

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

STUDENT LESSON A10 The String Class

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

More non-primitive types Lesson 06


More on variables and methods

String. Other languages that implement strings as character arrays

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

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

CPS 109 Lab 2 Alexander Ferworn Updated Fall 05. Ryerson University. School of Computer Science CPS109. Lab 2

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

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

JAVA NUMBERS, CHARS AND STRINGS

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

Class Library java.lang Package. Bok, Jong Soon

Lab #7 Library Classes and JUnit Testing. Daniel Amyot, Diana Inkpen, Alan. Agenda. In this lab, you are going to create your own

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

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

Java String Java String provides a lot of concepts that can be performed on a string such as compare, concat, equals, split, length, replace,

Programming with Java

CHAPTER 4 MATHEMATICAL FUNCTIONS, CHARACTERS, STRINGS

Module 4: Characters, Strings, and Mathematical Functions

Programming Techniques

Chapter 4 Mathematical Functions, Characters, and Strings

J.43 The length field of an array object makes the length of the array available. J.44 ARRAYS

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

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

CS 106A, Lecture 9 Problem-Solving with Strings

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

2. All the strings gets collected in a special memory are for Strings called " String constant pool".

Introductory Mobile Application Development

Lecture Notes K.Yellaswamy Assistant Professor K L University

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

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

Building Strings and Exploring String Class:

CS-140 Fall Binghamton University. Methods. Sect. 3.3, 8.2. There s a method in my madness.

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

+ Inheritance. n Superclass (base class) higher in the hierarchy. n Subclass (child class) lower in the hierarchy

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

Chapter 4. Mathematical Functions, Characters, and Strings

USING LIBRARY CLASSES

Today s plan Discuss the Bb quiz 1 Clarify Lab 1 Review basic Java materials Classes, Objects, Interfaces Strings Java IO. Understanding Board

Announcements. CompSci 100e Program Design and Analysis II

CS112 Lecture: Characters and Strings

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

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

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

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

What did we talk about last time? Math methods boolean operations char operations

Topics. Class Basics and Benefits Creating Objects.NET Architecture and Base Class Libraries 3-2

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

Java: Learning to Program with Robots

Lesson:9 Working with Array and String

Unit 4: Classes and Objects Notes

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

Voice Application Specification. SBString

Building Java Programs

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2008) Final Examination

Lecture 8: The String Class and Boolean Zen

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

Today s plan Discuss the Lab 1 Show Lab 2 Review basic Java materials Java API Strings Java IO

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

Welcome to the Using Objects lab!

Computer Science 252 Problem Solving with Java The College of Saint Rose Spring Topic Notes: Strings

Using Java Classes Fall 2018 Margaret Reid-Miller

Netbeans tutorial:

Java Foundations: Unit 3. Parts of a Java Program

Any serious Java programmers should use the APIs to develop Java programs Best practices of using APIs

STRINGS AND STRINGBUILDERS. Spring 2019

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

AP Computer Science A

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

Designing data types. Overview. Object Oriented Programming. Alan Kay. Object Oriented Programming (OOP) Data encapsulation. Checking for equality

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

CS 106A, Lecture 9 Problem-Solving with Strings

IS502052: Enterprise Systems Development Concepts Lab 1: Java Review

CHAPTER 6 MOST COMMONLY USED LIBRARIES

Designing data types. Fundamentals of Computer Science I

Faculty of Science COMP-202B - Introduction to Computing I (Winter 2009) - All Sections Final Examination

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

More on Strings. Lecture 10 CGS 3416 Fall October 13, 2015

Transcription:

Islamic University of Gaza Faculty of Engineering Computer Engineering Department Computer Programming Lab (ECOM 2124) Lab 2 String & Character Eng. Mohammed Abdualal

String Class In this lab, you have to be familiar how to deal with Strings. Strings : are a sequence of characters, Strings are Objects. The String class has thirteen constructors and more than forty methods Note: you have to learn almost of these constructors and methods about Strings. In this lab, we will learn an important constructors and methods and you have to be hardworking in another them. Creating Strings 1. The most direct way to create a string is to write: String greeting = "Hello world!"; 2. The most indirect way to create a string is to write: char[] helloarray = {'h', 'e', 'l', 'l', 'o', '.'; String hellostring = new String(helloArray); System.out.println(helloString); Immutable Strings A String object is immutable ; its contents cannot be changed. Does the following code change the contents of the string? String s = "Java"; s = "HTML"; The answer is no. The first statement creates a String object with the content "Java" and assigns its reference to s. The second statement creates a new String object with the content "HTML" and assigns its reference to s. The first String object still exists after the assignment, but it can no longer be accessed because variable s now points to the new object. Show below figure :

String Comparisons 1. Compare Objects in the same. The == operator as follows : if (string1 == string2) { System.out.println("string1 and string2 are the same object"); else { System.out.println("string1 and string2 are different objects"); 2. Compare of two Strings S1.equals(S2):Returns true if strings1 is equal to string S2. S1.equalsIgnoreCase(S2):Returns true if string S1 is equal to string S2 case insensitive(upper or lower). S1.compareTo(S2):Returns an integer value depends on the offset of the first two distinct characters in S1 and S2 from left to right in terms of Unicode ordering The returned value will be: 1. 0 if S1 is equal to S2. 2. >0 if S1 is greater than S2. 3. <0 if S1 is smaller than S2. S1.compareToIgnoreCase(S2):Same as compareto except that the comparison is case insensitive(upper or lower letter). TO distinguish between == Operator and equals method string. Look at the example below : String s1 = new String("Welcome to Java"); String s2 = "Welcome to Java"; System.out.println("s1==s2 is : " + (s1 == s2)); System.out.println("s1.equal(s2) is : " + (s1.equals(s2)));

When we use method intern see the result from the output code: String s1 = new String("Welcome to Java"); String s2 = "Welcome to Java"; System.out.println("s1. intern()==s2. intern() is : " + (s1.intern() == s2.intern())); System.out.println("s1.equal(s2) is : " + (s1.equals(s2))); String s1 = new String("Welcome to Java"); String s2 = "WelcOme To Java"; System.out.println("s1.equals(s2) is : " + (s1.equals(s2))); System.out.println("s1.equalsIgnoreCase(s2) is : " + (s1.equalsignorecase(s2))); System.out.println("s1.compareTo(s2) is : " + (s1.compareto(s2))); System.out.println("s1.compareToIgnoreCase(s2) is : " + (s1.comparetoignorecase(s2))); Output : String Length Returns the length of the string. String wlcmstr = "Welcome to Java II"; int len = wlcmstr.length(); System.out.println("The length of wlcmstr : "+len); Output :

s.charat(index) Method can be used to retrieve a specific character in a string s Index range from 0 to length 1 String wlcmstr = "Welcome to Java II"; System.out.println("Return the character in index 5 : "+wlcmstr.charat(5)); System.out.println("I love Palestine".charAt(10)); String Concatenation The String class includes a method for concatenating two strings: 1. Using + Operator 2. Using concat Method String s1 = "My name's "; String s2 = "Mohammed Abdual Al "; System.out.println(""+s1+" "+s2); System.out.println(""+s1.concat(s2));

Obtaining Substrings Obtain a substring from a string using the substring method in the String class. The substring method has two versions: substring(int beginindex, int endindex) Return substring begins at the specified beginindex and extends to the character at index endindex 1. substring(int beginindex) Return substring begins at the specified beginindex to the end of string. String S = "Welcome to Java"; System.out.println(S.substring(0, 11)); System.out.println(S.substring(11)); String Conversions

Finding a Character or a Substring in a String 1. public int indexof(string str) 2. (public int lastindexof(string str)) 3. public int indexof(string str, int fromindex) 4. (public int lastindexof(string str, int endindex)) Conversion Between Strings and Arrays Strings are not arrays, but a string can be converted into an array, and vice versa tochararray method : to convert String to array of character. String(char[]) method : to convert char of array(char[]) to String. Example: String S = "Welcome to Java"; char [] SCs = S.toCharArray();//To convert String to array of characters System.out.println(SCs[11]);//TO get character at index 11 from array of character SCs System.out.println(String.valueOf(SCs));//To convert array of characters to String

split(string s) Searches for a match as specified by the string argument. Example: String s = "T12009 a13 07"; String [] rstrings = s.split(" "); for (String string : rstrings) { System.out.println(string); trim() Returns a copy of this string with leading and trailing white space removed. Example: String s = " T12009 a13 07 "; System.out.println(s); System.out.println(s.trim());

touppercase() and tolowercase () Returns a copy of this string converted to lowercase or uppercase. If no conversions are necessary, these methods return the original string. Example: String s = "mohammed abdaalal"; System.out.println("toLowerCase : "+s.tolowercase()); System.out.println("toUpperCase : "+s.touppercase()); indexof () and lastindexof() Returns the index of the first (last)occurrence of the specified substring. Example: String s = "mohammed abdaalal"; System.out.println(""+s.indexOf("al")); System.out.println(""+s.lastIndexOf("al"));

StringTokenizer Class declaration StringTokenizer tokenizer = new StringTokenizer(s1); Class Methods int counttokens() This method calculates the number of times that this tokenizer's nexttoken method can be called before it generates an exception. boolean hasmoretokens() This method tests if there are more tokens available from this tokenizer's string. String nexttoken() This method returns the next token from this string tokenizer. Example :

Character Class Character class enables the char primitive data values to be treated as objects. It also contains useful methods for processing primitive values. Char charvalue =? CharValue is a character enclosed inside single quotes( ). Creating Character 1. The most direct way to create a character is to write: char ch = 'a'; // Unicode for uppercase Greek omega character char unichar = '\u039a'; // an array of chars char[] chararray ={ 'a', 'b', 'c', 'd', 'e' ; 2. The most indirect way to create a character is to write: Character ch = new Character('a'); Character ch = a ; Character Methods: Here is the list of the important instance methods that all the subclasses of the Character class implement: isletter() : Determines whether the specified char value is a letter. isdigit() : Determines whether the specified char value is a digit. iswhitespace() : Determines whether the specified char value is white space. isuppercase() : Determines whether the specified char value is uppercase. islowercase() : Determines whether the specified char value is lowercase. touppercase() : Returns the uppercase form of the specified char value. tolowercase() : Returns the lowercase form of the specified char value. tostring() : Returns a String object representing the specified character value that is, a one-character string.

Example (isletter(?)) String s = "T12009A1307"; char [] cs = s.tochararray(); for (int i = 0; i < cs.length; i++) { if(character.isletter(cs[i])){ System.out.println(""+cs[i]); Example (isdigit(?)) String s = "T12009A1307"; char [] cs = s.tochararray(); for (int i = 0; i < cs.length; i++) { if(character.isdigit(cs[i])){ System.out.print(""+cs[i]); Example (iswhitespace(?)) String s = "T12009 A13 07"; char [] cs = s.tochararray(); for (int i = 0; i < cs.length; i++) { if(character.iswhitespace(cs[i])){ System.out.println("Whitespace index : "+i);

Example (isuppercase(?) and islowercase(?)) String s = "T12009 a13 07"; char [] cs = s.tochararray(); for (int i = 0; i < cs.length; i++) { if(character.isuppercase(cs[i])){ System.out.println("isUpperCase : "+cs[i]); else if(character.islowercase(cs[i])){ System.out.println("isLowerCase : "+cs[i]); Example (touppercase(?) and tolowercase(?)) String s = "T12009 a13 07"; char [] cs = s.tochararray(); for (int i = 0; i < cs.length; i++) { if (Character.isLetter(cs[i])) { System.out.println("" + Character.toUpperCase(cs[i])); System.out.println("" + Character.toLowerCase(cs[i]));

Exercises: (Please I need this homework in one file.java and send it into my email). 1. Write a method that finds the number of occurrences of a specified character in the string using the following header: public static int count(string str, char a) For example, count("welcome", 'e') returns 2. 2. Write a method that counts the number of letters in the string using the following header: public static int countletters (String s); 3. Write a method that gets the sequence numbers from the string at the same order. public static int sequencenumbers(string s); For example, sequencenumbers("moh15a8me7 Ab8luala2"); Result 158782. 4. An anagram is a word or a phrase made by transposing the letters of another word or phrase; for example, "parliament" is an anagram of "partial men," and "software" is an anagram of "swear oft." Write a program that figures out whether one string is an anagram of another string. The program should ignore white space and punctuation. public static boolean areanagram (String s1,string s2);