← MATLAB EnglishChapter 09 of 13

String Manipulation

## Learning Objectives - Create and manipulate strings - Use string array functions - Convert between data types - Search and replace within strings ## Creating Strings ### Basic Strings ```matlab % Character vector (older style) c1 = 'Hello'; c2 = 'World'; % String scalar (R2016b+) s1 = "Hello"; s2 = "World"; ``` ### String Arrays ```matlab % Vector of strings names = ["John", "Jane", "Bob"]; % Create from character array c = 'Hello World'; s = string(c); % Create string array strArray = string({'Alice', 'Bob', 'Charlie'}); ``` ### Empty Strings ```matlab emptyChar = ''; emptyString = string(""); strWithSpaces = strings(1, 3); % 1x3 array of empty strings ``` ## String Operations ### Concatenation ```matlab % Horizontal concatenation s1 = "Hello"; s2 = "World"; s = [s1, s2] % "HelloWorld" s = strcat(s1, s2) % "HelloWorld" % With separator s = strjoin({s1, s2}, ' ') % "Hello World" ``` ### Joining String Arrays ```matlab names = ["Alice", "Bob", "Charlie"]; % Join with delimiter joined = strjoin(names, ', ') % "Alice, Bob, Charlie" % Join lines lines = strjoin(names, newline) ``` ### Replicate Strings ```matlab s = "Ha"; rep = repmat(s, 1, 3) % "HaHaHa" % Using strings function rep = strings(1, 3); rep(:) = "Hi"; ``` ## String Length ```matlab s = "Hello"; length(s) % 5 (string length) strlength(s) % 5 % For string array names = ["Alice", "Bob", "Charlie"]; strlength(names) % [5, 3, 9] ``` ## Extracting Substrings ### Extract Parts ```matlab s = "Hello World"; % Extract by position extract(s, [1, 5]) % "Hello" extract(s, [7, 11]) % "World" % Using colon s(1:5) % "Hello" s(7:end) % "World" ``` ### Split and Join ```matlab s = "Hello,World,2024"; split(s, ',') % ["Hello", "World", "2024"] splitlines(s) % Split by newlines % Join back strjoin({"A", "B", "C"}, '-') % "A-B-C" ``` ### Extract Between ```matlab s = "Hello(World)"; extractBetween(s, '(', ')') % "World" ``` ## Searching Strings ### Find Pattern ```matlab s = "Hello World"; % Contains contains(s, 'World') % true contains(s, 'world') % false (case-sensitive) contains(s, 'world', 'IgnoreCase', true) % true % StartsWith / EndsWith startsWith(s, 'Hello') % true endsWith(s, 'World') % true ``` ### Find Location ```matlab s = "Hello World"; % Pattern position idx = strfind(s, 'o') % [5, 8] (positions) % Using contains TF = contains(s, 'o') % Using == operator TF = (s == 'World') ``` ### String Comparison ```matlab s1 = "Hello"; s2 = "World"; s3 = "Hello"; % Equal strcmp(s1, s2) % false strcmp(s1, s3) % true % Equal ignoring case strcmpi(s1, 'hello') % true % Compare first n characters strncmp(s1, s3, 3) % true ``` ### Pattern Matching ```matlab s = "The quick brown fox"; % Using contains contains(s, 'brown') % Using regexp pat = "brown"; idx = strfind(s, pat) % Regex patterns regexp(s, '\w+') % Find all words ``` ## Replacing Strings ### Basic Replace ```matlab s = "Hello World"; % Replace substring newStr = replace(s, 'World', 'MATLAB') % "Hello MATLAB" newStr = replace(s, 'o', '0') % "Hell0 W0rld" ``` ### Multiple Replacements ```matlab s = "red blue red green"; % Replace multiple replace(s, {'red', 'blue'}, {'green', 'yellow'}) ``` ### Using regexprep ```matlab s = "Hello123World456"; % Regex replacement newStr = regexprep(s, '\d+', '#') % "Hello#World#" newStr = regexprep(s, '[0-9]', '0') % "Hello000World000" ``` ## String Case ```matlab s = "Hello World"; upper(s) % "HELLO WORLD" lower(s) % "hello world" title(s) % "Hello World" sentcase(s) % "Hello world" (sentence case) ``` ## Trim and Padding ```matlab s = " Hello "; trim(s) % "Hello" (remove leading/trailing spaces) s2 = "Hello"; pad(s2, 10) % " Hello" (pad to length 10) pad(s2, 10, 'both') % " Hello " ``` ## String Conversion ### Number to String ```matlab % Number to string num2str(42) % "42" num2str(3.14159, 4) % "3.142" % Integer to string int2str(42) % "42" % Using string (R2016b+) string(42) % "42" string(3.14) % "3.14" % Formatted string s = sprintf("Value: %.2f", 3.14159) % "Value: 3.14" ``` ### String to Number ```matlab % String to number str2double("42") % 42 str2num("42") % 42 % String to integer str2double("42") % With error handling str = "abc"; num = str2double(str); % NaN isnan(num) % true ``` ### Character Array Conversion ```matlab s = "Hello"; c = char(s) % 'Hello' c = ['H', 'e', 'l', 'l', 'o']; s = string(c) % "Hello" ``` ## String Formatting ### sprintf ```matlab name = "Alice"; age = 30; s = sprintf('Name: %s, Age: %d', name, age); % "Name: Alice, Age: 30" s = sprintf('Pi: %.4f', pi); % "Pi: 3.1416" ``` ### Formatting Options ```matlab % Width and precision sprintf('%10s', 'Hi') % " Hi" sprintf('%.2f', 3.14159) % "3.14" % Integer formatting sprintf('%05d', 42) % "00042" sprintf('%+d', 42) % "+42" ``` ## String Arrays with Missing Data ```matlab % String array with missing str = strings(1, 3); str(1) = "Alice"; str(2) = ""; str(3) = "Bob"; % Detect missing ismissing(str) % [false, true, false] % Replace missing str = replace(str, "", string(missing)); ``` ## String Patterns ### String Pattern Objects (R2020b+) ```matlab pat = pattern("Hello"); % Or with regex syntax pat = regexPattern("H\w+"); s = "Hello World"; extract(s, pat) % "Hello" contains(s, pat) % true ``` ## Summary - Use `string()` for string scalars, `["a", "b"]` for arrays - `strcat()` and `[s1, s2]` for concatenation - `split()` and `strjoin()` for splitting/joining - `replace()` for substring replacement - `contains()`, `startsWith()`, `endsWith()` for searching - `upper()`, `lower()`, `trim()` for transformations - `num2str()` and `str2double()` for conversion - `sprintf()` for formatted strings

Comments

Comments powered by Giscus

To enable comments, add your Giscus embed code here.

Learn more about Giscus →