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 finding the "@" character or other characters in the string?

- 111,146
- 38
- 238
- 371

- 10,768
- 34
- 94
- 129
7 Answers
You can use strread:
str = 'johndoe@hotmail.com';
[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 = '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
).

- 23,127
- 2
- 43
- 62
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.

- 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 = "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];
}

- 1,447
- 4
- 14
- 22