29.1k views
3 votes
write a c program to extract a substring from a given string. prompt the user to enter the starting position and length of the substring.

1 Answer

7 votes

Final answer:

The question is about creating a C program to extract a substring from a string. It includes prompts for user input for the starting position and length of the substring, demonstrating array indexing and a loop to achieve this.

Step-by-step explanation:

To extract a substring from a given string in C, you will need to use array indexing and a loop. Below is a simple C program that prompts the user to enter a string, the starting position, and the length of the substring they wish to extract.

#include
#include

int main() {
char str[100], sub[100];
int position, length, i;

printf("Enter a string: ");
gets(str);

printf("Enter the starting position of the substring: ");
scanf("%d", &position);

printf("Enter the length of the substring: ");
scanf("%d", &length);

for(i = 0; i < length; i++) {
sub[i] = str[position + i - 1];
}
sub[i] = '\0';

printf("The substring is: %s", sub);
return 0;
}
In this program, the gets function is used to read the input string, and then the user is asked to provide the starting position and the length of the substring. The loop is used to copy each character from the starting position to the designated length into the sub array. Take note that the starting position is treated as 1-based in this example. The final null character '\0' marks the end of the substring to ensure proper string termination.
User Ernesto Ruiz
by
9.1k points