390 likes | 492 Views
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?.
E N D
StringsCharacters 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? • 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 • Defining a string by hard-coding str = 'Fred Flintstone’; % Stored as: [70 114 101 100 32 70 108 105 110 116 115 116 111 110 101] • Creating with sprintf() str = sprintf('Curve of f(x)=%d + %dx',b,m);
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.
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.
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')
2. Creating Strings, cont. • Array-building str = 'Barney'; str = [str, ' Rubble was here']; • Concatenating name = 'Fred'; lastName = 'Flintstone'; str1 = [name, ' was', ' ' , 'here']; str2 = ['Hello Mr.', lastName, '. How are you?'];
2. Creating Strings, cont. • strcat() is used to combine strings, removing trailing whitespaces (trailing = end) str = strcat('Fred ','Flintstone',' was here ','! '); Expected: Fred Flintstone was here !
2. Creating Strings, cont. • 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.
3. Slicing Strings Assume: s = 'abcdefghijklmnopqrstuvwxyz'; • T = s(3:6) • X = s(1:3:10) • U = s(end:-1:22) Answer? T = 'c de' Answer? 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!
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) strfind() returns a vector containing theindices (positions) of the desired substring ' '. Allows multiple letters as substrings.
Example: Extract Data 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
StringsBuilt-In Functions Comparing Strings Converting strings/numbers Additional String Functions
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>
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
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)
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 00
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 00 • 2 letters were identical, 2 letters were not. But.. this does not give an overalltrue or false. So, let’s find another way to compare strings.
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 ==> 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..
1. Comparing Strings, cont. • Two built-in functions are commonly used to compare strings: • strcmp()– STRingCoMPare returns true if the two arguments (both strings) are identical (CaSesEnSItiVE) 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
1. Comparing Strings, cont. • Two built-in functions are commonly used to compare strings: • strcmpi()– STRingCoMPare 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 _____ 1 1 1 1
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
Example: Access Granted % ask for username username = input('Enter username: ', 's'); ifstrcmpi(username, 'John') % correct username %ask passwd pass = input('Enter password: ', 's'); ifstrcmp(pass, 'u23!9s2')%if correct password %grant access... else %quit/end code... end else % quit/end code... end 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()
Example: Dynamic prompts • Task: Introduce the sensor's number when prompting.
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.
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. 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)?”
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 % whileisnan() is true % grab again, convert again % Continue with calculations if it did
Example: Validating input • What does str2double() and isnan() do? • Example when string does look like a number:
Example: Validating input • What does str2double() and isnan() do? • Example when string has an ERROR:
Example: Validating input • Now, prompt the user for a value, then put the str2double() and isnan() in a loop! 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?
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) < 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