How Can Replacing Characters In A String?

C
Crosby · Sep 2, 2024 · 2K views
Question
I want to replace characters in a string using loops and if statements. For example if there is a Y in the string, I want to change it to a J. If there is an M in the string I want to change it to a Q.
Expert Answer
Profile picture of John Williams
John Williams PhD Expert
Answered Sep 15, 2026

In MATLAB, the modern and most versatile way to replace characters or substrings is using the replace() function: newStr = replace(str, oldText, newText). For advanced pattern matching (such as replacing digits, symbols, or whitespace), use regexprep(), and for position-specific modifications, use replaceBetween() or direct character vector indexing.

Top 5 Methods to Replace Characters in MATLAB

1. Modern Substring Replacement via replace() (Recommended)

The replace() function works seamlessly on string scalars, string arrays, and character vectors, and supports replacing multiple words simultaneously:

% Basic single replacement
originalStr = "MATLAB is slow for big data.";
updatedStr = replace(originalStr, "slow", "fast");
disp(updatedStr); % Output: "MATLAB is fast for big data."

% Multiple simultaneous replacements using array matching
rawText = "The red car parked next to the red building.";
cleanText = replace(rawText, ["red", "car"], ["blue", "truck"]);
disp(cleanText); % Output: "The blue truck parked next to the blue building."

% Vectorized replacement across entire string arrays
fileNames = ["sensor_test_v1.csv", "sensor_test_v2.csv", "sensor_test_v3.csv"];
correctedFiles = replace(fileNames, "test", "production");
disp(correctedFiles);

2. Regular Expression Replacement via regexprep()

Use regexprep() when you need pattern matching, such as sanitizing filenames, replacing numbers, or removing special symbols:

% Replace all digits (\d+) with an 'X'
serialCode = "Device-Model-9843-Batch-2024";
maskedCode = regexprep(serialCode, '\d+', 'XXXX');
disp(maskedCode); % Output: "Device-Model-XXXX-Batch-XXXX"

% Replace multiple spaces and tabs with a single space
messyText = "MATLAB    Simulink       Control";
cleanSpacing = regexprep(messyText, '\s+', ' ');
disp(cleanSpacing); % Output: "MATLAB Simulink Control"

% Remove all non-alphanumeric special characters
rawInput = "User#123_Profile$Data@2026!";
sanitized = regexprep(rawInput, '[^a-zA-Z0-9_]', '');
disp(sanitized); % Output: "User123_ProfileData2026"

3. Positional Replacement via replaceBetween()

If you want to replace characters between specific delimiter boundaries or fixed index ranges without modifying the rest of the text, use replaceBetween():

% Replace text inside parentheses
equation = "y = sin(theta_old) + cos(theta_old)";
newEquation = replaceBetween(equation, "(", ")", "x_new");
disp(newEquation); % Output: "y = sin(x_new) + cos(x_new)"

% Replace characters by numerical index range (positions 8 to 12)
code = "ABCDEF-OLDDATA-XYZ";
updatedCode = replaceBetween(code, 8, 14, "NEWVAL");
disp(updatedCode); % Output: "ABCDEF-NEWVAL-XYZ"

4. Direct Indexing on Character Arrays

For character vectors (enclosed in single quotes '...'), you can directly modify characters by their 1-based numerical index:

% Define character array
charVec = 'Python';

% Replace first letter directly
charVec(1) = 'M';
disp(charVec); % Output: 'Mython'

% Replace a slice of characters
charVec(1:3) = 'MAT';
disp(charVec); % Output: 'MATlon'

5. Removing Characters Completely via erase()

To delete characters without inserting a replacement, use erase() instead of replacing with an empty string:

phoneNum = "+1 (555) 234-5678";
cleanDigits = erase(phoneNum, ["+", "(", ")", " ", "-"]);
disp(cleanDigits); % Output: "15552345678"

Comparison of String Replacement Functions

Function Best Suited For Key Advantage
replace(str, old, new) General text and multi-word replacements. Modern, fast, and handles string arrays and cell arrays automatically.
regexprep(str, pattern, new) Complex wildcard matching, digits, symbols. Full regular expression power with lookahead and character classes.
replaceBetween(str, start, end, new) Replacing text within delimiters or index bounds. Safe positional replacement without altering matching text elsewhere.
erase(str, target) Deleting substrings or punctuation. Cleaner syntax than replace(str, target, "").
strrep(charVec, old, new) Legacy MATLAB scripts. Works on character arrays (superseded by replace()).

Key Best Practices

  • Use String Objects: Prefer double-quoted strings ("text") over single-quoted character arrays ('text') in modern MATLAB scripts for automatic vectorization and superior performance.
  • Case Sensitivity: replace() is case-sensitive by default. If you need case-insensitive replacements, use regexprep(str, 'pattern', 'new', 'ignorecase').
100% Run Guarantee 3-Hour Fast-Track Delivery

Need a Custom Version or Complete Simulation for This Problem?

Our 500+ PhD engineers build, debug, and optimize working MATLAB scripts and Simulink (.slx) models tailored to your exact assignment rubrics with zero plagiarism.

Tested on MATLAB R2024b / R2026a
Turnitin 0% Plagiarism Report
Free 7-Day Revisions Guarantee
Have a different question? Ask here

Get a Free Consultation or a Sample Assignment Review!