数学建模社区-数学中国

标题: 在一个字符串中查找/替换字符 [打印本页]

作者: 森之张卫东    时间: 2015-9-23 22:32
标题: 在一个字符串中查找/替换字符
      在一个字符串中查找/替换字符
MATLAB提供了许多的函数,用来对字符串中的字符进行查找或替换。考虑字符串test
test = 'This is a test!';
函数findstr返回短字符串在长字符串中所有的开始位置。例如为了寻找test内的所有“is”
>> position = findstr(test,'is')
position =
     3     6
字符串“is”在test内出现两次,开始位置分别为3和6。

函数strmatch是另一种匹配函数。它用来查看二维数组行开头的字符,并返回那些以指定的字符序列为开头行号。它的基本形式如下
result = strmatch(str,array);
例如,我们用strvcat创建一个二维数组,
array = strvcat('maxarray','min value','max value');
那么下面的语句将会返回开始字符为“max”的行数。
>> result = strmatch('max',array)
result =
     1
     3
函数strrep用于进行标准的查找和替换操作。它能找到一个字符串中的所有另一个字符串,并被第三个字符串替换。这个函数形式为
result = strrep(str,srch,repl)
其中str是被检测的字符串,srch是要查找到的字符串,repl是用于替代的字符串,例如,
>> result = strrep(test,'test','pest')
result =
This is a pest!
函数strtok返回输入字符串中第一次出现在分隔符前面的所有字符。默认的分隔符为一系列的空白字符。strtok的形式如下
[token, remainder] = strtok(string,delim)
其中string是输入字符串,delim是可选择的分隔符,token代表输入字符串中第一次出现在分隔符前面的所有字符,remainder代表这一行的其余部分。例如
>> [token, remainder] = strtok('This is a test!')
token =
This
remainder =
is a test!
你可以利用函数strtok把一个句子转换为单词。例如,下面的代码从字符数组input_string中分离出每一个单词,并把每一个单词独立地存储在字符数组all_words的每一行中。

function all_words = word(input_string)
remainder = input_string
all_words = '';
while (any(remainder))
    [chopped, remainder] =strtok(remainder);
    all_words =strvcat(all_words, chopped);
end







欢迎光临 数学建模社区-数学中国 (http://www.madio.net/) Powered by Discuz! X2.5