0
0
MATLABdata~5 mins

String replacement in MATLAB

Choose your learning style9 modes available
Introduction
String replacement helps you change parts of text easily, like fixing typos or updating words.
You want to correct a misspelled word in a sentence.
You need to update a date or name inside a text message.
You want to remove or replace certain characters from user input.
You want to change all occurrences of a word in a paragraph.
You want to format text by replacing placeholders with actual values.
Syntax
MATLAB
newStr = strrep(originalStr, oldSubstr, newSubstr);
strrep replaces all occurrences of oldSubstr with newSubstr in originalStr.
The function is case-sensitive and works on character arrays or string arrays.
Examples
Replaces 'world' with 'friend' resulting in 'hello friend'.
MATLAB
newStr = strrep('hello world', 'world', 'friend');
Replaces all 'a' letters with 'o', resulting in 'bonono'.
MATLAB
newStr = strrep('banana', 'a', 'o');
Changes 'fun' to 'great' in the sentence.
MATLAB
newStr = strrep('Matlab is fun', 'fun', 'great');
Sample Program
This program replaces every 'apples' with 'oranges' in the sentence and shows the new sentence.
MATLAB
originalStr = 'I love apples and apples are tasty.';
newStr = strrep(originalStr, 'apples', 'oranges');
disp(newStr);
OutputSuccess
Important Notes
strrep replaces all matches, not just the first one.
If oldSubstr is not found, the original string is returned unchanged.
Use double quotes for string arrays or single quotes for character arrays in MATLAB.
Summary
String replacement changes parts of text easily.
Use strrep(originalStr, oldSubstr, newSubstr) to replace all occurrences.
It works on both character arrays and string arrays.