Nic
Nic

Reputation: 93

Errors with splitting string

I'm quite new to programming and I'm trying to split the string below to just 36.20C but I keep getting ArgumentOutOfRangeWasUnhandled. why?

private void button1_Click(object sender, EventArgs e)
    {
        string inStr = "Temperature:36.20C";

        int indexOfSpace = inStr.IndexOf(':');
        //stores the address of the space 
        int indexOfC = inStr.IndexOf("C");
        //stores the address of char C

        string Temp = inStr.Substring(indexOfSpace + 1, indexOfC);

        textBox1.Text = Temp;
    }

expected output : 36.20C

Upvotes: 1

Views: 72

Answers (7)

David Arno
David Arno

Reputation: 43264

If you check the documentation for Substring, you'll see that the second parameter is the length, not the end position. However, there is an overload for SubString that only needs the start position and it'll return the string from there to the end of the string:

int indexOfSpace = inStr.IndexOf(':');
string Temp = inStr.Substring(indexOfSpace + 1);

Upvotes: 1

Saruchi
Saruchi

Reputation: 366

string temperature = "temperature:32.25C";
Console.WriteLine(temp.Substring(temp.Trim().IndexOf(':')+1));

In substring, 2nd argument is length and if u do not specify any argument substring processes till the end of string.

Upvotes: 0

DerAtrox
DerAtrox

Reputation: 183

Just use string.Split().

string[] temp = inStr.Split(':');
textbox1.Text = temp[1];
// temp[1] returns "36.20C"
// temp[0] returns "Temperature" 

Upvotes: 0

Afshar
Afshar

Reputation: 11543

Second parameter of Substring is length. You must update as following:

string Temp = inStr.Substring(indexOfSpace + 1, indexOfC - indexOfSpace);

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460298

The second argument of String.Substring is the length but you have provided the end index. You need to subtract them:

string Temp = inStr.Substring(++indexOfSpace, indexOfC - indexOfSpace);

You could also remove the C from the end:

string Temp = inStr.Substring(++indexOfSpace).TrimEnd('C'); // using the overload that takes the rest

As an aside, you should use the overload of IndexOf with the start-index in this case:

int indexOfC = inStr.IndexOf('C', indexOfSpace);

Here is an easier approach:

Temp = inStr.Split(':').Last().TrimEnd('C');

Upvotes: 4

Rohit Prakash
Rohit Prakash

Reputation: 1972

you can do it like

string Temp = inStr.Substring(indexOfSpace + 1, inStr.Length - indexOfSpace - 1)

Upvotes: 1

Kram
Kram

Reputation: 526

var arrayStr = inStr.split(':');
textbox1.text = arrayStr[1];

Upvotes: 1

Related Questions