Check if string starts with specific string in C# and VB.Net

Last Reply 26 days ago By irshad1231

Posted 26 days ago

Dear All,

I have a mobile number starting with 0 and 966. Like below

0123456789

966123456789

I trying to remove 0 and 966 from the string but want to check the string starting with 0 or 966.

I'm using the below code

string mobileno = "966123456789";//starting with 966
string finalmobileno = Regex.Replace(nationalID, "966", "", RegexOptions.IgnoreCase);
lbl_mobile.Text = finalmobileno.ToString();

string mobileno ="0123456789";//starting with 0
string finalmobileno = iqamano.Substring(1);
lbl_mobile.Text = finalmobileno.ToString();

How can I do it one to check both?

Thanks

Posted 26 days ago

Hi irshad1231,

Check this example. Now please take its reference and correct your code.

C#

string mobileno = "966123456789";
string finalmobileno = "";
if (mobileno.StartsWith("966")) //starting with 966
{
    finalmobileno = Regex.Replace(mobileno, "^966", "", RegexOptions.IgnoreCase); // Replace starting 966.
}
Response.Write(finalmobileno.ToString() + "<br/>");

string iqamano = "0123456789";
if (iqamano.StartsWith("0")) //starting with 0
{
    finalmobileno = Regex.Replace(iqamano, "^0", "", RegexOptions.IgnoreCase); // Replace starting 0.
}
Response.Write(finalmobileno.ToString());

VB.Net

Dim mobileno As String = "966123456789"
Dim finalmobileno As String = ""
If mobileno.StartsWith("966") Then 'starting with 966
    finalmobileno = Regex.Replace(mobileno, "^966", "", RegexOptions.IgnoreCase) 'Replace starting 966.
End If
Response.Write(finalmobileno.ToString() & "<br/>")
Dim iqamano As String = "0123456789"

If iqamano.StartsWith("0") Then 'starting with 0
    finalmobileno = Regex.Replace(iqamano, "^0", "", RegexOptions.IgnoreCase) 'Replace starting 0.
End If
Response.Write(finalmobileno.ToString())

Output

123456789

123456789


Posted 26 days ago Modified on 26 days ago

Try this without Regex simple and easy.

string mobileno = "966123456789";
string finalmobileno = "";
if (mobileno.StartsWith("966")) //starting with 966
{
    finalmobileno = mobileno.Substring(mobileno.IndexOf("966") +3);
}
lbl_mobile.Text = finalmobileno.ToString();

string iqamano = "0123456789";
if (iqamano.StartsWith("0")) //starting with 0
{
    finalmobileno = iqamano.Substring(iqamano.IndexOf("0") +1);
}
lbl_mobile.Text = finalmobileno.ToString();

Posted 26 days ago

I'm doing this as below. It's working.

if (mobileno.StartsWith("966"))
{
    lbl_mobile.Text = mobileno.Remove(0, 3);
}
else
{
    lbl_mobile.Text = mobileno.Remove(0, 1);
}