在MATLAB中的字符串的每一行中添加一个子字符串 [英] Adding a substring to each line in a string in MATLAB
问题描述
假设我在MATLAB中的变量中有一个字符串,如下所示:
Say I have a string in a variable in MATLAB like the following:
this is the first line
this is the second line
this is the third line
我想在每行的开头添加一个固定的字符串.例如:
I would like to add a fixed string at the beginning of each line. For example:
add_substring(input_string, 'add_this. ')
将输出:
add_this. this is the first line
add_this. this is the second line
add_this. this is the third line
我知道我可以通过遍历输入字符串来做到这一点,但是我正在寻找一种更紧凑的(希望是矢量化的)方式来实现这一点,也许使用诸如arrayfun
accumarray
之类的MATLAB内置函数之一.
I know I can do this by looping through the input string, but I am looking for a more compact (hopefully vectorized) way to do this, perhaps using one of MATLAB built-ins such as arrayfun
accumarray
.
推荐答案
strcat
函数就是您所需要的.它确实对字符串进行向量化连接.
The strcat
function is what you're looking for. It does vectorized concatenation of strings.
strs = {
'this is the first line'
'this is the second line'
'this is the third line'
}
strcat({'add_this. '}, strs)
使用strcat时,您需要将'add_this. '
放入单元格({}
)中,以防止其尾部的空白被删除,这是strcat对于char输入的正常行为.
With strcat, you need to put 'add_this. '
in a cell ({}
) to protect it from having its trailing whitespace stripped, which is strcat's normal behavior for char inputs.
这篇关于在MATLAB中的字符串的每一行中添加一个子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!