19

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?

Shai
  • 111,146
  • 38
  • 238
  • 371
stanigator
  • 10,768
  • 34
  • 94
  • 129

7 Answers7

17

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) = '';
gnovice
  • 125,304
  • 15
  • 256
  • 359
12

You can use strread:

str = 'johndoe@hotmail.com';
[a b] = strread(str, '%s %s', 'delimiter','@')
a = 
    'johndoe'
b = 
    'hotmail.com'
Amro
  • 123,847
  • 25
  • 243
  • 454
11

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

kenm
  • 23,127
  • 2
  • 43
  • 62
7

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

mtrw
  • 34,200
  • 7
  • 63
  • 71
5

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.

Shai
  • 111,146
  • 38
  • 238
  • 371
SnakeEyes1482
  • 93
  • 1
  • 6
-1

I used strtok and strrep from Matlab instead.

stanigator
  • 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
-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];
    }
sachin
  • 1,447
  • 4
  • 14
  • 22