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

时间:2009-09-15 04:42:14

标签: string matlab

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

7 个答案:

答案 0 :(得分:17)

STRTOK并且索引操作应该可以解决问题:

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

或者最后一行也可以是:

address(1) = '';

答案 1 :(得分:12)

您可以使用 strread

str = 'johndoe@hotmail.com';
[a b] = strread(str, '%s %s', 'delimiter','@')
a = 
    'johndoe'
b = 
    'hotmail.com'

答案 2 :(得分: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)。

答案 3 :(得分:7)

TEXTSCAN也有效。

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

返回一个单元格数组,其中部分{1}为'johndoe',部分{2}为'hotmail.com'。

答案 4 :(得分:5)

如果此线程现在还没有完全枚举,我可以添加另一个吗?一个方便的基于perl的MATLAB函数:

email = 'johndoe@hotmail.com';
parts = regexp(email,'@', 'split');

parts是一个双元素单元格数组,类似于mtrw的textscan实现。也许是矫枉过正,但是当通过多个分隔字符或模式搜索分割字符串时,regexp会更有用。唯一的缺点是使用正则表达式,经过15年的编码,我仍然没有掌握它。

答案 5 :(得分:-1)

我使用了来自Matlab的strtok和strrep。

答案 6 :(得分:-4)

String 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];
    }