Skip to main content

Unable to extract a substring from a string [Resolved]

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;

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.

Question Credit: Maven
Question Reference
Asked June 11, 2016
Tags: , .net, substring
Posted Under: Programming
5 Answers

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)

credit: Justin Pihony
Answered June 11, 2016

Try changing

fileInStringTemp = fileInString.Substring(cStart, cEnd);


fileInStringTemp = fileInString.Substring(cStart, cPhase);

credit: dazedandconfused
Answered June 11, 2016

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.)

credit: Wonderbird
Answered June 11, 2016

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

credit: DesertIvy
Answered June 11, 2016
Your Answer