+ All Categories
Home > Documents > Strings Characters and Sentences

Strings Characters and Sentences

Date post: 15-Feb-2016
Category:
Upload: stamos
View: 40 times
Download: 0 times
Share this document with a friend
Description:
Strings Characters and Sentences. Overview Creating Strings Slicing Strings Searching for substrings. 1. Strings, overview. Strings are arrays of characters Str = ' This is 21 characters ' ;. Spaces count as 1 characters too!. But what about the 1’s and 0’s?. - PowerPoint PPT Presentation
39
Strings Characters and Sentences 1. Overview 2. Creating Strings 3. Slicing Strings 4. Searching for substrings 1
Transcript
Page 1: Strings Characters and Sentences

1

StringsCharacters and Sentences

1. Overview2. Creating Strings3. Slicing Strings4. Searching for substrings

Page 2: Strings Characters and Sentences

1. Strings, overview.

• Strings are arrays of charactersStr = 'This is 21 characters';

2

Spaces count as 1 characters too!

T h i s i s 2 1 c h a r a c t e r s

Page 3: Strings Characters and Sentences

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.

Page 4: Strings Characters and Sentences
Page 5: Strings Characters and Sentences

2. Creating Strings

1. Defining a string by hard-codingstr = 'Fred Flintstone’;

% Stored as: [70 114 101 100 32 70 108 105 110 116 115 116 111 110 101]

2. Creating with sprintf()str = sprintf('Curve of f(x)=%d + %dx',b,m);

5

Page 6: Strings Characters and Sentences

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

Page 7: Strings Characters and Sentences

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

Page 8: Strings Characters and Sentences

Example: sprintf(), cont.

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

8

Page 9: Strings Characters and Sentences

2. Creating Strings, cont.

3. Array-buildingstr = 'Barney';str = [str, ' Rubble was here'];

4. Concatenatingname = 'Fred';lastName = 'Flintstone';str1 = [name, ' was', ' ' , 'here'];str2 = ['Hello Mr.', lastName, '. How are you?'];

9

Page 10: Strings Characters and Sentences

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

Page 11: Strings Characters and Sentences

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

Page 12: Strings Characters and Sentences

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?

Answer?

U = 'zyxwvu t'

Page 13: Strings Characters and Sentences

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

Page 14: Strings Characters and Sentences

Example: Extract Data

% prompt user for full namestr = input('What is your full name (first middle

last)? ', 's');

% Find the spacesindices = strfind(str, ' '); %indices =find(str==' ');

% Extract each separate namesFirst = 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.

Page 15: Strings Characters and Sentences

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)

Page 16: Strings Characters and Sentences

Example: Dates

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

16

Page 17: Strings Characters and Sentences

17

StringsBuilt-In Functions

1. Comparing Strings2. Converting strings/numbers3. Additional String Functions

Page 18: Strings Characters and Sentences

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' <enter>

Page 19: Strings Characters and Sentences

19

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' <enter>ans = 1 1 1 1

Page 20: Strings Characters and Sentences

20

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' <enter>ans = 1 1 1 1

• MATLAB evaluates equality letter by letter, assigning a 0 (for false) or a 1 (for true)

Page 21: Strings Characters and Sentences

21

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' <enter>ans = 1 1 0 0

Page 22: Strings Characters and Sentences

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, whether str is equal to 'Frog'%(note that it is not, so we expect a false!)>> str == 'Frog' <enter>ans = 1 1 0 0

• 2 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.

Page 23: Strings Characters and Sentences

23

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' <enter>??? Error using ==> eqMatrix 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..

Page 24: Strings Characters and Sentences

24

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

0

1

1

Page 25: Strings Characters and Sentences

25

1. Comparing Strings, cont.

• Two built-in functions are commonly used to compare strings:

1. strcmpi()– STRing CoMPare Insensitivereturns 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 _____

1

1

1

1

Page 26: Strings Characters and Sentences

Example: Access Granted

% ask for usernameusername = input('Enter username: ', 's');

if %correct username% ask for a passwd

if %correct passwordgrant access…

elsequit/end code

endelse % quit/end codeend

26

Page 27: Strings Characters and Sentences

Example: Access Granted

% ask for usernameusername = 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

Page 28: Strings Characters and Sentences

28

2. Converting strings

• Convert: string numbersstr2num()str2double() [will convert an entire cell arrays of strings]

• Convert: number stringint2str()num2str()

Page 29: Strings Characters and Sentences

Example: Dynamic prompts

• Task: Introduce the sensor's number when prompting.

29

Page 30: Strings Characters and Sentences

30

Example: Dynamic prompts

• One way is as a combination of an fprintf() and an input() command:

%loop to prompt for each valuefor position = 1:nbSensors fprintf('Enter value of sensor #%d:',position); table(position) = input(' '); %leave a spaceend

• 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.

Page 31: Strings Characters and Sentences

31

Example: Dynamic prompts

• Another way: using string concatenation

%loop to prompt for each valuefor 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.

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

Page 32: Strings Characters and Sentences

Example: Validating input

• “What happens when the user enters letters (instead of numbers)?”

32

Page 33: Strings Characters and Sentences

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

Page 34: Strings Characters and Sentences

Example: Validating input

• What does str2double() and isnan() do?

• Example when string does look like a number:

34

Page 35: Strings Characters and Sentences

Example: Validating input

• What does str2double() and isnan() do?

• Example when string has an ERROR:

35

Page 36: Strings Characters and Sentences

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.

Page 37: Strings Characters and Sentences

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

Page 38: Strings Characters and Sentences

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

Page 39: Strings Characters and Sentences

function ValidInt = GetBoundedInt( Prompt, LowerLimit, UpperLimit )% Prompts for an integer between 2 values %Print prompt and collect input as a stringValidInt = input(Prompt, 's'); %Identify if input is a number%Identify if input is between lower and upper limits%As long as input is invalidwhile( isnan( str2double( ValidInt )) || str2double(ValidInt) < LowerLimit || 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


Recommended