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
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
).
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.
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) = '';
You can use strread:
str = 'johndoe@hotmail.com';
[a b] = strread(str, '%s %s', 'delimiter','@')
a =
'johndoe'
b =
'hotmail.com'
I used strtok and strrep from Matlab instead.
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'.