I have the following method:
public static string PrepareNumberForInserting(string pNumber)
{
if (pNumber.Length > 7)
{
if (pNumber.Length == 8 && pNumber.Substring(0, 1) == "7")
{
pNumber = pNumber.Substring(1, 8);
}
if (pNumber.Length == 9 && pNumber.Substring(0, 2) == "07")
{
pNumber = pNumber.Substring(2, 9);
}
if (pNumber.Length == 11 && pNumber.Substring(0, 4) == "3897")
{
pNumber = pNumber.Substring(4, 11);
}
if (pNumber.Length == 12 && pNumber.Substring(0, 5) == "38907")
{
pNumber = pNumber.Substring(5, 12);
}
}
else
{
pNumber = string.Format("3897{0}", pNumber);
}
return pNumber;
}
regardless of what format the user enters his number (be it 070300067, 70300067, xxx70300067), i want to extract the last 7 characters and prefix them with 3897. If I enter anything other than 7xxxxxx i get a Exception Details: System.ArgumentOutOfRangeException: Index and length must refer to a location within the string.
Any idea? Thank you very much!
Edit:
I solved my problem in the following way:
public static string PrepareNumberForInserting(string pNumber)
{
if (pNumber.Length > 7)
{
if (pNumber.Length == 8 && pNumber.StartsWith("7"))
{
pNumber = pNumber.Substring(1);
}
if (pNumber.Length == 9 && pNumber.StartsWith("07"))
{
pNumber = pNumber.Substring(2);
}
if (pNumber.Length == 11 && pNumber.StartsWith("3897"))
{
pNumber = pNumber.Substring(4);
}
if (pNumber.Length == 12 && pNumber.StartsWith("38907"))
{
pNumber = pNumber.Substring(5);
}
}
pNumber = string.Format("3897{0}", pNumber);
return pNumber;
}
Thank you all for taking the time to answer my question!
Look at the documentation for
Substring:The second parameter to substring is a length, not the end index. Thus code like:
Will take characters 5 to 16, and not 5 to 11 as you expected. Since your string has only 12 characters this leads to the
ArgumentOutOfRangeExceptionyou observed.To fix the problem, you can either calculate the length (
length=endIndex-startIndex+1), or if you need everything after a certain index you can simply use the other overload: