Suppose I have a string '[email protected]'
. I want to store the string before and after "@" into 2 separate strings. What would be the easiest method of finding the "@" character or other characters in the string?

- 111,146
- 38
- 238
- 371

- 10,768
- 34
- 94
- 129
7 Answers
STRTOK and an index operation should do the trick:
str = '[email protected]';
[name,address] = strtok(str,'@');
address = address(2:end);
Or the last line could also be:
address(1) = '';

- 125,304
- 15
- 256
- 359
You can use strread:
str = '[email protected]';
[a b] = strread(str, '%s %s', 'delimiter','@')
a =
'johndoe'
b =
'hotmail.com'

- 123,847
- 25
- 243
- 454
-
1note: recent versions of MATLAB recommend using `textscan` instead of `strread` – Amro Apr 19 '13 at 06:08
For "easiest",
>> email = '[email protected]'
email =
[email protected]
>> 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
).

- 23,127
- 2
- 43
- 62
TEXTSCAN works too.
str = '[email protected]';
parts = textscan(str, '%s %s', 'Delimiter', '@');
returns a cell array where parts{1} is 'johndoe' and parts{2} is 'hotmail.com'.

- 34,200
- 7
- 63
- 71
If this thread isn't completely enumerated by now, may I add another? A handy perl-based MATLAB function:
email = '[email protected]';
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.

- 111,146
- 38
- 238
- 371

- 93
- 1
- 6
I used strtok and strrep from Matlab instead.

- 10,768
- 34
- 94
- 129
-
4-1. The other answers are better here since they provide example code. How did you use `strtok` and `strrep`? Show an example and I'll flip to a +1. – gary Apr 05 '11 at 13:06
String email = "[email protected]";
String a[] = email.split("@");
String def = null;
String ghi = null;
for(int i=0;i<a.length;i++){
def = a[0];
ghi = a[1];
}

- 1,447
- 4
- 14
- 22