C Exercises: Reverse a string partially
Write a C program that takes a string and two integers (n1, n2). Now reverse the sequence of characters in the string between n1 and n2.
Let l be the length of the string.
Constraints:
- 1 ≤ n1 ≤ n2 ≤ l ≤100
- Each letter of the string is an uppercase or lowercase letter.
Sample Date:
("abcdxyabcd", 5, 6) -> "abcdyxabcd"
("Exercises", 1, 3) -> "exercises"
C Code:
#include <stdio.h> // Include standard input/output library
#include <string.h> // Include string handling library
int main(void)
{
char text[101] = {0}; // Declare an array 'text' to hold the input string
char result[101] = {0}; // Declare an array 'result' to hold the modified string
int n1, n2, l; // Declare variables for position inputs and string length
// Prompt the user to input a string
printf("Input a string: ");
// Read the input string from the user and store it in the 'text' array
scanf("%s", text);
// Prompt the user to input position-1 for reversing the string
printf("Input position-1 for reverse the string: ");
// Read the position-1 input from the user and store it in 'n1'
scanf("%d", &n1);
// Prompt the user to input position-2 for reversing the string
printf("\nInput position-2 for reverse the string: ");
// Read the position-2 input from the user and store it in 'n2'
scanf("%d", &n2);
l = strlen(text); // Calculate the length of the input string and store it in 'l'
int i = 0;
// Copy characters from the start of 'text' to 'result' until position-1
for(; i< n1-1; i++) {
result[i] = text[i];
}
// Reverse and copy characters from position-2 to position-1 in 'text' to 'result'
for(int j = n2-1; i< n2; i++, j--) {
result[i] = text[j];
}
// Copy the remaining characters from 'text' to 'result'
for(; i<= l; i++) {
result[i] = text[i];
}
// Print the modified string
printf("Reverse string (partly): %s\n", result);
return 0;
}
Sample Output:
Input a string: Input position-1 for reverse the string: abcdxyabcd 5 6 Input position-2 for reverse the string: Reverse string (partly): abcdyxabcd
Flowchart:
C Programming Code Editor:
Previous C Programming Exercise: Find the integer that appears the least often.
Next C Programming Exercise: Second largest among three integers.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics