How to Find a Substring in MATLAB

Save

Strings of text are stored in MATLAB as vectors (single-row matrices). Individual characters in strings can be retrieved just as elements in a vector (e.g., stringname(4)). MATLAB also includes a number of commands to help you work with strings. Use the "strfind" command to search a string for a particular character or set of characters (substring).

  • Type the following command in the Command Window to create a new string, being sure to use single quotation marks:

    mystring = 'This is an example string.';

  • Use "strfind" to search "mystring" for the letter "i:"

    strfind(mystring,'i')

    The numbers 3, 6 and 23 are returned in a vector. These numbers correspond to the indices in "mystring" where "i" was found (the third, sixth and 23rd letters).

  • Use a string for the second argument to find a longer substring:

    strfind(mystring,'example')

    The number 12 is returned. This corresponds to the 12th character in the string, where the word "example" begins.

References

  • Photo Credit Hemera Technologies/AbleStock.com/Getty Images
Promoted By Zergnet

Comments

Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

M
Is DIY in your DNA? Become part of our maker community.
Submit Your Work!