MATLAB strrep 函数查找并替换字符串中的子串,返回替换后的新字符串,也可一次处理字符串数组。
语法
newStr = strrep(str, old, new)输入参数
| 参数 | 说明 |
|---|---|
str | 原始文本:字符数组、字符串数组或 cell 数组 |
old | 要被替换掉的子串 |
new | 替换成的新子串 |
输出
newStr 为替换后的文本,类型与 str 保持一致;原字符串不被修改。
示例
基本替换:
strrep('Hello World', 'World', 'MATLAB')ans = 'Hello MATLAB'替换所有出现位置:
strrep('a-b-c-d', '-', '+')ans = 'a+b+c+d'批量替换 cell 数组:
names = {'Reva Dutta', 'Zara Ali'};
strrep(names, 'Reva', 'Poulomi')ans =
1x2 cell
{'Poulomi Dutta'} {'Zara Ali'}替换字符串数组:
s = ["hello world", "hello matlab"];
strrep(s, "hello", "hi")ans =
1x2 string
"hi world" "hi matlab"注意事项
- 若
old为空字符串,会把new插入到每个字符之间(极少用,注意别误传空串); - 想支持正则表达式替换,用
regexprep; - 大小写敏感,想忽略大小写可先
lower统一。