1
StringsCharacters and Sentences
1. Overview2. Creating Strings3. Slicing Strings4. Searching for substrings
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
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-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
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 properlystr = sprintf('Curve of f(x)=%d + %dx',b,m);title(str)xlabel('x')ylabel('y')
8
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
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?
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 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.
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
17
StringsBuilt-In Functions
1. Comparing Strings2. Converting strings/numbers3. Additional String Functions
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>
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
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)
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
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.
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..
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
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
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
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
28
2. Converting strings
• Convert: string numbersstr2num()str2double() [will convert an entire cell arrays of strings]
• Convert: number stringint2str()num2str()
Example: Dynamic prompts
• Task: Introduce the sensor's number when prompting.
29
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.
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
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 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