Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get String after String.indexof in c#

I am currently developing an application in C# where I need to get the substring after a certain character within the string.

else if (txtPriceLimit.Text.Contains('.') && char.IsNumber(e.KeyChar))
{
    int index = txtPriceLimit.Text.IndexOf('.');
    string pennies = txtPriceLimit.Text.Substring(index, txtPriceLimit.Text.Length);
    Console.WriteLine("Pennies: " + pennies);
}

For some reason it keeps on coming up with an IndexOutOfRangeException. How can I get the contents of the string from the index to the end?

Thanks for any help you can provide.

EDIT: Just found that the various things I have tried that have been suggested do seem to work except its not getting the value from the last button pressed into the text field. I am using the KeyPress Event in order to do this.

For example if I enter .123 it will only print 12. Then if I add 4 on the end it will print 123

like image 897
Boardy Avatar asked Feb 24 '11 17:02

Boardy


1 Answers

The overload of String.Substring that you're using takes a start index and a specified length. As the start index, you're using the location of ".", but as the length, you're using the length of the entire string. If index is greater than 0, this will cause an exception (as you've seen).

Instead, just use this:

string pennies = txtPriceLimit.Text.Substring(index + 1);

This will get all of the characters within txtPriceLimit.Text after the location of ".". Note that we need to add 1 to the index; otherwise "." will be included in the resulting substring.

like image 79
Donut Avatar answered Sep 22 '22 05:09

Donut