假设我有一个字符串 'johndoe@hotmail.com'.我想将"@"之前和之后的字符串存储到2个单独的字符串中.在字符串中查找"@"字符或其他字符最简单的方法是什么?
gno*_*ice 17
STRTOK和索引操作应该可以解决问题:
str = 'johndoe@hotmail.com';
[name,address] = strtok(str,'@');
address = address(2:end);
Run Code Online (Sandbox Code Playgroud)
或者最后一行也可以是:
address(1) = '';
Run Code Online (Sandbox Code Playgroud)
Amr*_*mro 12
你可以使用strread:
str = 'johndoe@hotmail.com';
[a b] = strread(str, '%s %s', 'delimiter','@')
a =
'johndoe'
b =
'hotmail.com'
Run Code Online (Sandbox Code Playgroud)
kwa*_*ord 11
对于"最简单",
>> email = 'johndoe@hotmail.com'
email =
johndoe@hotmail.com
>> email == '@'
ans =
Columns 1 through 13
0 0 0 0 0 0 0 1 0 0 0 0 0
Columns 14 through 19
0 0 0 0 0 0
>> at = find(email == '@')
at =
8
>> email(1:at-1)
ans =
johndoe
>> email(at+1:end)
ans =
hotmail.com
Run Code Online (Sandbox Code Playgroud)
如果您正在寻找具有多个字符的内容,或者您不确定是否只有一个@,那将会稍微复杂一点,在这种情况下,MATLAB有很多用于搜索文本的函数,包括正则表达式(见doc regexp).
TEXTSCAN也有效.
str = 'johndoe@hotmail.com';
parts = textscan(str, '%s %s', 'Delimiter', '@');
Run Code Online (Sandbox Code Playgroud)
返回一个单元格数组,其中部分{1}是'johndoe'而部分{2}是'hotmail.com'.
小智 5
如果此线程现在还没有完全枚举,我可以添加另一个吗?一个方便的基于perl的MATLAB功能:
email = 'johndoe@hotmail.com';
parts = regexp(email,'@', 'split');
Run Code Online (Sandbox Code Playgroud)
parts是一个双元素单元格数组,类似于mtrw的textscan实现.也许是矫枉过正,但是当通过多个分隔字符或模式搜索来分割字符串时,regexp会更有用.唯一的缺点是使用正则表达式,经过15年的编码,我仍然没有掌握它.
sta*_*tor -1
我使用 Matlab 中的 strtok 和 strrep 代替。