0

I have a email id like below

string email=test.mail@test.com;
string myText = email.split("."); 

i am not sure who split first two characters and followed by two characters after the period or dot.

myText = tema //(desired output)
Alan Moore
  • 73,866
  • 12
  • 100
  • 156
Selva
  • 431
  • 2
  • 7
  • 13

4 Answers4

3

Use LINQ ;)

string myText = string.Join("", email.Remove(email.IndexOf('@')).Split('.')
                                .Select(r =>new String(r.Take(2).ToArray())));
  • First Remove text after @, (including @)
  • Then split on .
  • From the returned array take first two characters from each element and convert it to array
  • Pass the array of characters to String constructor creating a string
  • using String.Join to combine returned strings element.
Habib
  • 219,104
  • 29
  • 407
  • 436
  • ,is it possible, can i get the first letter as Captial in the return string value? – Selva Oct 24 '14 at 18:48
  • myText = Tema // I want the result is like this where the return string's first character is a captial letter – Selva Oct 24 '14 at 18:48
  • @Selva, that is a separate issue and it already has too many answers here on stackoverflow. See http://stackoverflow.com/questions/4135317/make-first-letter-of-a-string-upper-case-for-maximum-performance – Habib Oct 24 '14 at 18:51
2

Another Linq solution:

string first = new string(email.Take(2).ToArray());
string second = new string(email.SkipWhile(c => c != '.').Skip(1).Take(2).ToArray());
string res = first + second;
w.b
  • 11,026
  • 5
  • 30
  • 49
1
string.Join(string.Empty, email.Substring(0, email.IndexOf("@")).Split('.').Select(x => x.Substring(0, 2)));
dariogriffo
  • 4,148
  • 3
  • 17
  • 34
1

Lots of creative answers here, but the most important point is that Split() is the wrong tool for this job. It's much easier to use Replace():

myText = Regex.Replace(email, @"^(\w{2})[^.]*\.(\w{2})[^.]*@.+$", "$1$2");

Note that I'm making a lot of simplifying assumptions here. Most importantly, I'm assuming the original string contains the email address and nothing else (you're not searching for it), that the string is well formed (you're not trying to validate it), and that both of substrings you're interested in start with at least two word characters.

Alan Moore
  • 73,866
  • 12
  • 100
  • 156