w3resource

C Exercises: Reverse a string partially

C Basic-II: Exercise-2 with Solution

Write a C program that takes a string and two integers (n1, n2). Now reverse the sequence of characters of 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 <string.h>

int main(void)
{
    char text[101] = {0};
    char result[101] = {0};
    int n1, n2, l; 
    printf("Input a string: ");
    scanf("%s", text);
    printf("Input position-1 for reverse the string: ");
    scanf("%d", &n1);
    printf("\nInput position-2 for reverse the string: ");
    scanf("%d", &n2);
        
    l = strlen(text);
    int i = 0;
    for(; i < n1-1; i++) {
        result[i] = text[i];
    }
    for(int j = n2-1; i < n2; i++, j--) {
        result[i] = text[j];
    }
    for(; i <= l; i++) {
        result[i] = text[i];
    }

    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 Flowchart: Reverse a string partially.

C Programming Code Editor:

Contribute your code and comments through Disqus.

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.



Follow us on Facebook and Twitter for latest update.

C Programming: Tips of the Day

Reading a string with scanf :

An array "decays" into a pointer to its first element, so scanf("%s", string) is equivalent to scanf("%s", &string[0]). On the other hand, scanf("%s", &string) passes a pointer-to-char[256], but it points to the same place.

Then scanf, when processing the tail of its argument list, will try to pull out a char *. That's the Right Thing when you've passed in string or &string[0], but when you've passed in &string you're depending on something that the language standard doesn't guarantee, namely that the pointers &string and &string[0] -- pointers to objects of different types and sizes that start at the same place -- are represented the same way.

Ref : https://bit.ly/3pdEk6f