在Matlab中查找字符串中的特定字符

19

假设我有一个字符串'johndoe@hotmail.com',我想把“@”前后的字符串存储到2个单独的字符串中。找到字符串中“@”或其他字符的最简单方法是什么?

7个回答

17

STRTOK和索引操作可以解决问题:

str = 'johndoe@hotmail.com';
[name,address] = strtok(str,'@');
address = address(2:end);

最后一行也可以是这样:

address(1) = '';

12
您可以使用strread函数:
str = 'johndoe@hotmail.com';
[a b] = strread(str, '%s %s', 'delimiter','@')
a = 
    'johndoe'
b = 
    'hotmail.com'

1
注意:MATLAB的最新版本建议使用textscan代替strread - Amro

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

如果你正在寻找超过一个字符的内容或者不确定是否恰好有一个 @,那么情况会稍微复杂一些。在这种情况下,MATLAB 有很多搜索文本的函数,包括正则表达式(请参阅 doc regexp)。


7

TEXTSCAN也可以使用。

str = 'johndoe@hotmail.com';
parts = textscan(str, '%s %s', 'Delimiter', '@');

返回一个单元数组,其中parts {1}是“johndoe”,parts {2}是“hotmail.com”。


5
如果这个帖子还没有被完全列举,我可以再添加一个吗?一个方便的基于Perl的MATLAB函数:
email = 'johndoe@hotmail.com';
parts = regexp(email,'@', 'split');

parts是一个类似于mtrw的textscan实现的两个元素单元数组。也许有些过度,但当需要用多个分隔符或模式搜索来拆分字符串时,使用正则表达式更加有效。唯一的缺点就是需要使用正则表达式,即使我已经编码15年了,仍然没有掌握。


+1很奇怪,这么长时间里没有人提到正则表达式 :) - Amro

-1
我使用了Matlab中的strtok和strrep函数。

4
其他回答更好,因为它们提供了示例代码。你如何使用strtokstrrep?请给出一个示例,我会将评分调整为+1。 - gary

-4

字符串 email = "johndoe@hotmail.com";

    String a[] = email.split("@");
    String def = null;
    String ghi = null;
    for(int i=0;i<a.length;i++){
        def = a[0];
        ghi = a[1];
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接