user971741
user971741

Reputation:

Unable to extract a substring from a string

I am long string array and i want to pass it to another function in the chunks of 250 characters one time, i have written this code:

var cStart = 0;
var phase = 250;
var cEnd = cStart + phase;
var count = 0;

while (count < 10000)
{
    string fileInStringTemp = "";
    fileInStringTemp = fileInString.Substring(cStart, cEnd);
    var lngth = fileInStringTemp.Length;

    //Do Some Work

    cStart += phase;
    cEnd += phase;
    count++;
}

In the first iteration of the loop the value of lngth is 250 which is fine, in the next iteration i also want it to 250 because i am extracting substring from 250-500 characters but shockingly the value of lngth variable in the second iteration gets 500.

Why is that? i am also trying to initialize string variable everytime in the loop so it starts from zero but no gain.

Upvotes: 0

Views: 135

Answers (5)

Aashish Kumar
Aashish Kumar

Reputation: 1643

Here is the MSDN link about how to work with Substring:

https://msdn.microsoft.com/en-us/library/aka44szs(v=vs.110).aspx

According to MSDN first parameter in Substring method is StartIndex which is defined as The zero-based starting character position of a substring and second parameter is used to define lenght of substring which is defined as The number of characters in the substring.

So you should try this:

var cStart = 0;
var phase = 250;
var count = 0;

while (count < 10000)
{
    string fileInStringTemp = "";
    fileInStringTemp = fileInString.Substring(cStart, phase);
    var lngth = fileInStringTemp.Length;

    //Do Some Work
    count++;
    cStart = phase * count + 1;
}

Upvotes: 7

Kai
Kai

Reputation: 1

Substring has the parameters (startIndex, count) so you are not aloud to increment end. better change to Substring(cStart, phase)

Upvotes: 0

Wonderbird
Wonderbird

Reputation: 374

The 2nd parameter to your SubString() method is the length of the substring to return. (You should be able to always use 250 and just keep shifting your starting point - the 1st param - until you are done.)

Upvotes: 0

dazedandconfused
dazedandconfused

Reputation: 3186

Try changing

fileInStringTemp = fileInString.Substring(cStart, cEnd);

to

fileInStringTemp = fileInString.Substring(cStart, cPhase);

Upvotes: 2

Justin Pihony
Justin Pihony

Reputation: 67075

Substring's second parameter is the length you want, not the stop index.

public string Substring(
    int startIndex,
    int length
)

So, all you need to do is change your code to have the start index and length (phase)

fileInString.Substring(cStart, phase)

Upvotes: 9

Related Questions