1 / 39

Strings Characters and Sentences

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

stamos
Download Presentation

Strings Characters and Sentences

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. StringsCharacters and Sentences Overview Creating Strings Slicing Strings Searching for substrings

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

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

  4. 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);

  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. • 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?'];

  9. 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 !

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

  11. 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'

  12. 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) strfind() returns a vector containing theindices (positions) of the desired substring ' '. Allows multiple letters as substrings.

  14. 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)

  15. Example: Dates • Using the MM/DD/YYYY format for a birthday parse out the: • Month • Day • Year

  16. StringsBuilt-In Functions Comparing Strings Converting strings/numbers 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' <enter>

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

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

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

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

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

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

  25. 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'); 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

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

  31. 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 % whileisnan() 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! EXTREMELY IMPORTANT: isnan() MUST BE THE FIRST CONDITION.

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

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

More Related