user175084
user175084

Reputation: 4640

Replace char in a string

how to change

[email protected] into XXX_YYY_ZZZ

One way i know is to use the string.replace(char, char) method,

but i want to replace "@" & "." The above method replaces just one char.

one more case is what if i have [email protected]...

i still want the output to look like XX.X_YYY_ZZZ

Is this possible?? any suggestions thanks

Upvotes: 0

Views: 1823

Answers (7)

Ahmad Mageed
Ahmad Mageed

Reputation: 96557

Here's a complete regex solution that covers both your cases. The key to your second case is to match dots after the @ symbol by using a positive look-behind.

string[] inputs = { "[email protected]", "[email protected]" };
string pattern = @"@|(?<=@.*?)\.";

foreach (var input in inputs)
{
    string result = Regex.Replace(input, pattern, "_");
    Console.WriteLine("Original: " + input);
    Console.WriteLine("Modified: " + result);
    Console.WriteLine();
}

Although this is simple enough to accomplish with a couple of string Replace calls. Efficiency is something you will need to test depending on text size and number of replacements the code will make.

Upvotes: 4

Zafer
Zafer

Reputation: 2190

Assuming data format is like [email protected], here is another alternative with String.Split(char seperator):

string[] tmp = "[email protected]".Split('@');
string newstr = tmp[0] + "_" + tmp[1].Replace(".", "_");

Upvotes: 0

kbrimington
kbrimington

Reputation: 25692

You can use the following extension method to do your replacement without creating too many temporary strings (as occurs with Substring and Replace) or incurring regex overhead. It skips to the @ symbol, and then iterates through the remaining characters to perform the replacement.

public static string CustomReplace(this string s)
{
    var sb = new StringBuilder(s);
    for (int i = Math.Max(0, s.IndexOf('@')); i < sb.Length; i++)
        if (sb[i] == '@' || sb[i] == '.')
            sb[i] = '_';
    return sb.ToString();
}

Upvotes: 3

Bob
Bob

Reputation: 3351

So, if I'm understanding correctly, you want to replace @ with _, and . with _, but only if . comes after @? If there is a guaranteed @ (assuming you're dealing with e-mail addresses?):

string e = "[email protected]";
e = e.Substring(0, e.IndexOf('@')) + "_" + e.Substring(e.IndexOf('@')+1).Replace('.', '_');

Upvotes: 8

MRR0GERS
MRR0GERS

Reputation: 654

Create an array with characters you want to have replaced, loop through array and do the replace based off the index.

Upvotes: 0

Pharabus
Pharabus

Reputation: 6062

you can chain replace

var newstring =    "[email protected]".Replace("@","_").Replace(".","_");

Upvotes: 0

Related Questions