Strings Characters and Sentences 1.Overview 2.Creating Strings 3.Slicing Strings 4.Searching for substrings 1.

Slides:



Advertisements
Similar presentations
Computer Science & Engineering 2111 Text Functions 1CSE 2111 Lecture-Text Functions.
Advertisements

Chapter 7. Even in quantitative sciences, we often encounter letters and/or words that must be processed by code You may want to write code that: Reads.
An Introduction to Python – Part II Dr. Nancy Warter-Perez.
Example – calculating interest until the amount doubles using a for loop: will calculate up to 1000 years, if necessary if condition decides when to terminate.
CIS 101: Computer Programming and Problem Solving Lecture 7 Usman Roshan Department of Computer Science NJIT.
1 Outline 13.1Introduction 13.2A Simple Program: Printing a Line of Text in a Web Page 13.3Another JavaScript Program: Adding Integers 13.4Memory Concepts.
Additional Data Types: 2-D Arrays, Logical Arrays, Strings Selim Aksoy Bilkent University Department of Computer Engineering
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Lecture 3 Sept 3 Complete Chapter 3 Exercises quiz.
Week 6 - Programming I So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands Today, extend features to:
Lecture 3 August 31 Chapter 3. Chapter 3 – numbers, string, booleans integer: MATLAB stores numeric data as double-precision floating point (double) by.
Introduction to Python
Insight Through Computing 15. Strings Operations Subscripting Concatenation Search Numeric-String Conversions Built-Ins: int2str,num2str, str2double.
Additional Data Types: Strings Selim Aksoy Bilkent University Department of Computer Engineering
MATLAB Strings Selim Aksoy Bilkent University Department of Computer Engineering
Chapter 9 Creating Formulas that Manipulate Text Microsoft Office Excel 2003.
Creating scalars, vectors, matrices Ex1 & 2. Dot Product & Cross Product Ex3. Plotting Graphs Ex4. Conversion Table Ex5. Plotting functions Finishing Ex4.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
Tutorial 14 Working with Forms and Regular Expressions.
1 Lab Session-III CSIT-120 Fall 2000 Revising Previous session Data input and output While loop Exercise Limits and Bounds Session III-B (starts on slide.
A453 Exemplar Password Program using VBA
Noadswood Science,  To understand what strings are and how decisions are made Thursday, September 17, 2015.
Introduction to Python
REVIEW 2 Exam History of Computers 1. CPU stands for _______________________. a. Counter productive units b. Central processing unit c. Copper.
IPC144 Introduction to Programming Using C Week 1 – Lesson 2
07/10/ Strings ASCII& Processing Strings with the Functions - Locate (Instr), Mid, Length (Len), Char (ChrW) & ASCII (Asc)
Mastering Char to ASCII AND DOING MORE RELATED STRING MANIPULATION Why VB.Net ?  The Language resembles Pseudocode - good for teaching and learning fundamentals.
1 Functions 1 Parameter, 1 Return-Value 1. The problem 2. Recall the layout 3. Create the definition 4. "Flow" of data 5. Testing 6. Projects 1 and 2.
Input, Output, and Processing
Strings The Basics. Strings can refer to a string variable as one variable or as many different components (characters) string values are delimited by.
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
1. Exam Topics Difference between computers and calculators John creates a new device. It will compute the orbit of all the planets in the solar system.
COMP 116: Introduction to Scientific Programming Lecture 24: Strings in MATLAB.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
Asking the USER for values to use in a software 1 Input.
Arrays II (Strings). Data types in C Integer : int i; Double: double x; Float: float y; Character: char ch; char cha[10], chb[]={‘h’,’e’,’l’,’l’,’o’};
Lecture 5 1.What is a variable 2.What types of information are stored in a variable 3.Getting user input from the keyboard 1.
Data Structures & Algorithms
More Strings CS303E: Elements of Computers and Programming.
Lecture 26: Reusable Methods: Enviable Sloth. Creating Function M-files User defined functions are stored as M- files To use them, they must be in the.
Strings Mr. Smith AP Computer Science A. What are Strings? Name some of the characteristics of strings: A string is a sequence of characters, such as.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
Decision Structures, String Comparison, Nested Structures
C++ String Class nalhareqi©2012. string u The string is any sequence of characters u To use strings, you need to include the header u The string is one.
Asking the USER for values to use in a software 1 Input.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
Lecture 6: Output 1.Presenting results in a professional manner 2.semicolon, disp(), fprintf() 3.Placeholders 4.Special characters 5.Format-modifiers 1.
CECS 5020 Computers in Education Visual Basic Variables and Constants.
CMPS 1371 Introduction to Computing for Engineers CHARACTER STRINGS.
1. Comparing Strings 2. Converting strings/numbers 3. Additional String Functions Strings Built-In Functions 1.
CS 170 – INTRO TO SCIENTIFIC AND ENGINEERING PROGRAMMING.
DCT1063 Programming 2 CHAPTER 3 STRINGS Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
CSC 162 Visual Basic I Programming. String Functions LTrim( string ) –Removes leading spaces from the left side of string RTrim( string ) –Removes trailing.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 this week – last section on Friday. Assignment 4 is posted. Data mining: –Designing functions.
Strings CSCI 112: Programming in C.
Introduction to Scripting
Strings Part 1 Taken from notes by Dr. Neil Moore
String Manipulation Part 2
String Manipulation Chapter 7 Attaway MATLAB 4E.
4.1 Strings ASCII & Processing Strings with the Functions
String manipulation string.h library
String Processing 1 MIS 3406 Department of MIS Fox School of Business
Introduction to Computer Science
JavaScript: Introduction to Scripting
Text Manipulation Chapter 7 Attaway MATLAB 5E.
Python Strings.
Strings Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Presentation transcript:

Strings Characters and Sentences 1.Overview 2.Creating Strings 3.Slicing Strings 4.Searching for substrings 1

1. Strings, overview. Strings are arrays of characters Str = 'This is 21 characters'; 2 Spaces count as 1 characters too! Thisis21characters

But what about the 1’s and 0’s? Letters are stored internally as numbers. The “letter to number coding” is a standardized encoding called ASCII. Used/supported in almost every other computer programming language. Other encodings generally start with ASCII as the basis.

2. Creating Strings 1.Defining a string by hard-coding str = 'Fred Flintstone’; % Stored as: [ ] 2.Creating with sprintf() str = sprintf( ' Curve of f(x)=%d + %dx ',b,m); 5

Example: sprintf() Prompt the user for the slope and y-intercept of a line, then plot. The title of the plot must reflect the current equation of the line. 6

Example: sprintf(), cont. FACT: The function title() requires 1 and only 1 string argument: title( ) This would NOT work: title('Curve of %d+%dx.', b, m)  sprintf() is used to create 1 string variable. This string variable is used in the title() command. 7

Example: sprintf(), cont. %ask for slope (m) and y-intercept (b) … %create x and y data points, then plot … plot(x,y) %label plot properly str = sprintf('Curve of f(x)=%d + %dx',b,m); title(str) xlabel('x') ylabel('y') 8

2. Creating Strings, cont. 3.Array-building str = 'Barney'; str = [str, ' Rubble was here']; 4.Concatenating name = 'Fred'; lastName = 'Flintstone'; str1 = [name, ' was', ' ', 'here']; str2 = ['Hello Mr.', lastName, '. How are you?']; 9

2. Creating Strings, cont. 5. strcat() is used to combine strings, removing trailing whitespaces (trailing = end) str = strcat('Fred ','Flintstone',' was here ','! '); Expected: Fred Flintstone was here ! 10

2. Creating Strings, cont. 5.strcat() is used to combine strings, removing trailing whitespaces (trailing = end) str = strcat('Fred ','Flintstone',' was here ','! '); Expected: Fred Flintstone was here ! Got: FredFlintstone was here! It does NOT get rid of leading spaces. 11

3. Slicing Strings Assume: s = 'abc defghi jklmnopqrst uvwxyz'; T = s(3:6) X = s(1:3:10) U = s(end:-1:22) 12 Answer? T = 'c de' X = 'a fi' Answer? U = 'zyxwvu t'

Example: Extract Data From a string, “parse” the data, i.e. extract each word separately. Humans find the spaces first, then extract the 3 names in a split second. MATLAB can do exactly the same! 13

Example: Extract Data % prompt user for full name str = input('What is your full name (first middle last)? ', 's'); % Find the spaces indices = strfind(str, ' '); %indices =find(str==' '); % Extract each separate names First = str(1:indices(1)-1) Middle = str((indices(1)+1):(indices(2)-1)) Last = str((indices(2)+1):end) 14 strfind() returns a vector containing the indices (positions) of the desired substring ' '. Allows multiple letters as substrings.

Example: Extract Data 15 First = str(1: indices(1)-1 ) = str(1: 5-1) = str(1:4) Middle= str(indices(1)+1 : indices(2)-1) = str( 5+1 : 10-1 ) = str(6:9) Last = str(indices(2)+1 : end) = str(10+1 : end) = str(11:end)

Example: Dates Using the MM/DD/YYYY format for a birthday parse out the: – Month – Day – Year 16

Strings Built-In Functions 1.Comparing Strings 2.Converting strings/numbers 3.Additional String Functions 17

1. Comparing Strings Curious: What would using == do? %hardcode a string. Set in stone. We know what it is. str = 'Fred'; %test in command window, whether str is equal to 'Fred' %(note that it is, so we expect a true!) >> str == 'Fred' 18

1. Comparing Strings Curious: What would using == do? %hardcode a string. Set in stone. We know what it is. str = 'Fred'; %test in command window, whether str is equal to 'Fred' %(note that it is, so we expect a true!) >> str == 'Fred' ans =

1. Comparing Strings Curious: What would using == do? %hardcode a string. Set in stone. We know what it is. str = 'Fred'; %test in command window, whether str is equal to 'Fred' %(note that it is, so we expect a true!) >> str == 'Fred' ans = MATLAB evaluates equality letter by letter, assigning a 0 (for false) or a 1 (for true) 20

1. Comparing Strings, cont. Curious: What would using == do? %hardcode a string. Set in stone. We know what it is. str = 'Fred'; %test in command window, whether str is equal to 'Frog' %(note that it is not, so we expect a false!) >> str == 'Frog' ans =

1. Comparing Strings, cont. Curious: What would using == do? %hardcode a string. Set in stone. We know what it is. str = 'Fred'; %test in command window, whether str is equal to 'Frog' %(note that it is not, so we expect a false!) >> str == 'Frog' ans = letters were identical, 2 letters were not. But.. this does not give an overall true or false. So, let’s find another way to compare strings. 22

1. Comparing Strings, cont. Curious: What would using == do? %hardcode a string. Set in stone. We know what it is. str = 'Fred'; %test in command window, is str equal to 'Flintstones'? %(note that it is not, so we expect a false!) >> str == 'Flintstone' ??? Error using ==> eq Matrix dimensions must agree. It even gets worse when the length of each string does not match.. It creates an error. Definitely not the right method to compare strings.. 23

1. Comparing Strings, cont. Two built-in functions are commonly used to compare strings: 1.strcmp() – STRing CoMPare returns true if the two arguments (both strings) are identical (CaSe sEnSItiVE) Practice: strcmp('hi', 'hi') evaluates to ______ Practice: strcmp('HI', 'hi') evaluates to ______ Practice: str = 'yes'; strcmp(str, ‘yes') evaluates to _____ strcmp(‘yes', str) evaluates to _____

1. Comparing Strings, cont. Two built-in functions are commonly used to compare strings: 1.strcmpi() – STRing CoMPare Insensitive returns true if the two arguments (both strings) are identical WITHOUT REGARD TO CASE Practice: strcmpi('hi', 'hi') evaluates to ______ Practice: strcmpi('HI', 'hi') evaluates to ______ Practice: str = 'yes'; strcmpi(str, 'Yes') evaluates to _____ strcmpi('YeS', str) evaluates to _____

Example: Access Granted % ask for username username = input('Enter username: ', 's'); if %correct username % ask for a passwd if %correct password grant access… else quit/end code end else % quit/end code end 26

Example: Access Granted % ask for username username = input('Enter username: ', 's'); if strcmpi(username, 'John') % correct username %ask passwd pass = input('Enter password: ', 's'); if strcmp(pass, 'u23!9s2') %if correct password %grant access... else %quit/end code... end else % quit/end code... end 27 The user name may not be case-sensitive… …but a password is usually case-sensitive

2. Converting strings Convert: string  numbers str2num() str2double () [will convert an entire cell arrays of strings] Convert: number  string int2str() num2str() 28

Example: Dynamic prompts Task: Introduce the sensor's number when prompting. 29

Example: Dynamic prompts One way is as a combination of an fprintf() and an input() command: %loop to prompt for each value for position = 1:nbSensors fprintf('Enter value of sensor #%d:',position); table(position) = input(' '); %leave a space end CAUTION: they cannot be combined. The input() command accepts only 1 string argument, or 2 when prompting for a string ( 's' ).  input() never accepts placeholders and variable names. 30

Example: Dynamic prompts Another way: using string concatenation %loop to prompt for each value for position = 1:nbSensors prompt = ['Enter value of sensor #', int2str(position), ': ']; table(position) = input(prompt); end CAUTION: the [] must be there to concatenate the 3 pieces (first part of the sentence, the number, and the colon) into 1 string. 31 Convert the integer to a string before concatenating all 3 pieces. The digit 1 becomes the string '1', the digit 2 becomes the string '2', etc

Example: Validating input “What happens when the user enters letters (instead of numbers)?” 32

Example: Validating input To solve this problem, every input must now be considered as a string, even if they are numbers! Algorithms possible % Grab user's input as strings % Use str2double() to convert to numbers % Use isnan() to check if the conversion worked % Continue with calculations if it did % Grab user's input as strings % Use str2double() to convert to numbers % while isnan() is true % grab again, convert again % Continue with calculations if it did 33

Example: Validating input What does str2double() and isnan() do? Example when string does look like a number: 34

Example: Validating input What does str2double() and isnan() do? Example when string has an ERROR: 35

Example: Validating input Now, prompt the user for a value, then put the str2double() and isnan() in a loop! 36 EXTREMELY IMPORTANT: isnan() MUST BE THE FIRST CONDITION.

3. Additional String Functions lower() – converts a string to lowercase upper() – converts a string to uppercase isletter() – which characters in the string are letters? 37

Get Bounded Integer Write a function that accepts a prompt, a lower limit, and an upper limit and validate the input, re-prompting until the user enters a valid number. Algorithm: %Print prompt and collect input as a string %Identify if input is a number %Identify if input is between lower and upper limits %As long as input is invalid, print an error message and re-prompt

function ValidInt = GetBoundedInt( Prompt, LowerLimit, UpperLimit ) % Prompts for an integer between 2 values %Print prompt and collect input as a string ValidInt = input(Prompt, 's'); %Identify if input is a number %Identify if input is between lower and upper limits %As long as input is invalid while( isnan( str2double( ValidInt )) || str2double(ValidInt) UpperLimit ) %print an error message and re-prompt fprintf('Enter a valid integer between %d and %d\n', LowerLimit, UpperLimit ); ValidInt = input(Prompt, 's'); end