Ebrahim ElSayed
Ebrahim ElSayed

Reputation: 177

How to replace a specific string using method?

I have problem with my code , I want to replace specific string to a new one but it doesn't work

public void InsertYahoo(TextBox sender)
{
    if (IsGmail(sender))
    {
        ReplaceGmail(sender);
    }
    else if(IsYahoo(sender))
    {
        return;
    }
    else
    {
        sender.Text +="@yahoo.com";
    }
}

public bool IsYahoo(TextBox sender)
{
    if (sender.Text.Contains("@yahoo.com")
    {
        return true;
    }
    else
    { 
        return false;
    }
}

public bool IsGmail(TextBox sender)
{ 
    if (sender.Text.Contains("@gmail.com") 
    {
        return true;
    }
    else
    { 
        return false;
    }
}

public void ReplaceGmail(TextBox sender)
{
    sender.Text.Replace("@gmail.com, "@yahoo.com");
}

This code what i tried , so any suggestions? Also I tried to get the index of @gmail.com and remove it but it did not work neither

Upvotes: 1

Views: 89

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460078

Strings are immutable, so every method in the String class does not modify the current instance but returns a new one. You have to assign this to the original variable:

sender.Text = sender.Text.Replace("@gmail.com,"@yahoo.com");

If you are interested in why strings are immutable: Why .NET String is immutable?

Upvotes: 3

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

Something like this:

//DONE: we should check for null
//DONE: it's Yahoo if it ends on @yahoo.com (not contains)
public static bool IsYahoo(TextBox sender) =>
  sender != null && 
  sender.Text.TrimEnd().EndsWith("@yahoo.com", StringComparison.OrdinalIgnoreCase);

public static bool IsGmail(TextBox sender) =>
  sender != null && 
  sender.Text.TrimEnd().EndsWith("@gmail.com", StringComparison.OrdinalIgnoreCase);

public static void InsertYahoo(TextBox sender) {
  if (null == sender)
    throw new ArgumentNullException(nameof(sender));

  if (IsYahoo(sender))
    return;

  // Uncomment, In case you want to change gmail only
  //if (!IsGmail(sender)) 
  //  return;

  // If we have an eMail like bla-bla-bla@somewhere
  int p = sender.Text.LastIndexOf('@');

  // ... we change somewhere to yahoo.com
  if (p > 0)
    sender.Text = sender.Text.Substring(0, p) + "@yahoo.com";


} 

Upvotes: 1

Related Questions