# Extract a substring from a string without using the library function.[C# Console Application] [closed]

My Solution for Question 13 on https://www.w3resource.com/csharp-exercises/string/index.php

        Console.Write("Please enter your word : ");

Console.Write("Starting position : ");

Console.Write("Number of letters : ");

int x = word.Length - numberOfLetters;

int end = word.Length - x;

for (int counter = start; counter <= end; counter++)
{
Console.Write(word[counter]);
}


• Please summarise the problem statement (in your own words, of course). The link may be helpful while it lasts, but questions are expected to be complete without needing external resources. Thanks! Commented Jan 8, 2020 at 21:14

You are not really extracting a substring, you are only printing a substring.

A string consists of single characters of type char. Create an array of chars and then convert it to string

var characters = new char[numberOfLetters];
for (int i = 0; i < numberOfLetters; i++) {
characters[i] = word[i + start];
}
string output = new String(characters);


You are doing a strange calculation

int x = word.Length - numberOfLetters;
int end = word.Length - x;


If you insert the first expression for x into the second, you get:

int end = word.Length - (word.Length - numberOfLetters);


which is equivalent to

int end = word.Length - word.Length + numberOfLetters;


or

int end = numberOfLetters;


which is not correct. Simply add start and numberOfLetters to get the exclusive upper bound. If printing the substring is a solution, then you can write:

int max = start + numberOfLetters;
for (int i = start; i < max; i++) {
Console.Write(word[i]);
}