Finding a specific character in a string in Matlab

前端 未结 7 1114
闹比i
闹比i 2020-12-16 13:02

Suppose I have a string \'johndoe@hotmail.com\'. I want to store the string before and after \"@\" into 2 separate strings. What would be the easiest method of

相关标签:
7条回答
  • 2020-12-16 13:16

    For "easiest",

    >> 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
    

    It would be slightly more complicated if you were looking for something with more than one character, or you weren't sure if there was exactly one @, and in that case MATLAB has a lot of functions for searching through text, including regular expressions (see doc regexp).

    0 讨论(0)
  • 2020-12-16 13:17

    If this thread isn't completely enumerated by now, may I add another? A handy perl-based MATLAB function:

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

    parts is a two element cell array similar to mtrw's implementation of textscan. Maybe overkill, but regexp is much more useful when splitting a string by multiple delimiting characters or pattern searching. The only downside is the use of regular expressions which I still haven't mastered after 15 years of coding.

    0 讨论(0)
  • 2020-12-16 13:21

    STRTOK and an index operation should do the trick:

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

    Or the last line could also be:

    address(1) = '';
    
    0 讨论(0)
  • 2020-12-16 13:27

    You can use strread:

    str = 'johndoe@hotmail.com';
    [a b] = strread(str, '%s %s', 'delimiter','@')
    a = 
        'johndoe'
    b = 
        'hotmail.com'
    
    0 讨论(0)
  • 2020-12-16 13:32

    I used strtok and strrep from Matlab instead.

    0 讨论(0)
  • 2020-12-16 13:40

    TEXTSCAN works too.

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

    returns a cell array where parts{1} is 'johndoe' and parts{2} is 'hotmail.com'.

    0 讨论(0)
提交回复
热议问题