String Reverse function in C

In this post, we will basically focus on the String Reverse function in C. Now before starting the discussion of string reverse function, I think we should also discuss some basics of strings and string library functions.

So, without wasting your time let’s start!

Introduction

Strings are basically defined as an array of characters. The difference between a character array and a string is that the string is terminated with a special character known as ‘\0’.

Declaration

Declaration of strings: Declaring a string is very simple. Below is the basic syntax for declaring a string.

char string_name[size];

In the given syntax string_name is a name is given to the string variable and size. It is used to define the length of the string. It is important to know that there is an extra terminating character which is the Null character (‘\0’).

The null character is used to indicate the termination of string which differs strings from normal character arrays.

For more information, you can refer to our article on string and arrays

Let us look at a simple program to get a clear understanding of how declaring and initializing a string in C works. We will also learn on how to print a string.

#include<stdio.h>
  
int main()
{   
    // declaring and initializing string
    char str[] = "GeeksToCode";
      
    // print a string
    printf("%s",str);
    return 0;
}

We can see that in the above program, strings can be printed using normal printf statements. As it was in arrays, we do not need to print a string here character by character.

The C language basically does not provide any inbuilt data type for strings. rather, it has something called an access specifier “%s” that can be used to directly print and read strings.

Try this question- Do you know the difference between:


char amessage[ ] = “message”
char *pmessage = “message”


Answer:
char amessage[ ] = “message” // single array
char *pmessage = “message” // pointer and array
m e s s a g e \0

—> m e s s a g e \0

I/O with Strings

char * outputString = “Hello”;
char inputString [100];

Printf and scanf use “%s” format characters for strings.

Printf basically print characters up to terminating zero.
Example: printf(“%s”, outputString);

Scanf read characters until whitespace and stores the result in string and terminate with zero
Example: scanf(“%s”, inputString);

Although there is no string data type in C, C has a library that can perform actions on strings. All the functions have parameters or return values:

  1. As character arrays terminated with a null character.
  2. Const char * i.e. declares a pointer to a const (string constant)

E.g. of String function-

  1. strlen – returns the string length
  2. strcpy – copy one string to another location

C String Library

C mainly has a limited string library. All are based on null-terminated strings.

Functions include

  1. int strlen(const char* str)
  2. void strcpy(char* dest, const char* src)
  3. int strcmp(const char* s1, const char* s2) Returns 0 on equal, -1 or 1 if greater or less

If not equal, then the sign is based on the difference between bytes in the location the strings differ in. Remember, 0 is false, so equal returns false!

How to take Input as string and print Output that string?

Way 1:

void main()
{
char name[30];
printf("Enter your name");
scanf("%s", name); //format specifier
printf("%s", name);
}


Way 2:

void main()
{
char name[30];
printf("Enter your name");
gets(name); //in-built function
puts(name);
}

The difference between both ways is that 1st-way use’s format specifier and the second way uses
in-built function.


In 1st way, if you enter something like Bob Charles it will take only Bob as a string and anything after (space) will be discarded. In a second way if you enter any space it will be
accepted.


The output of the second way would be Bob Charles.


Similarity between both way is that you don’t have to add ‘\0’ character.

scanf(%s ) converts 32(space) or ‘\n’ character into ‘\0’ and gets() converts newline
character ‘\n’ into ‘\0’.

List of (most frequently used) string library functions in c.

strlen strcpy strcat strrev strcmp strcmpi strupr strlwr strncmpi strncat strncmp strncmpi strncmpi. String functions examples

1) int strlen(char array): This function accepts a string as a parameter and returns an integer i.e the length of the string passed to it.

2) strcpy (Destination string,source string):This function accepts 2 strings as parameter,1st one is destination string and 2nd is source string. This function copies source string to destination string.

3) strcat (Destination string,source string): This function accepts two strings source string is appended to the destination string.

4) strrev (string):This function accepts single string as parameter and reverse that string.

5)int strcmp (string 1, string2):This function compares two strings passed as parameters and returns either +ve number,0,-ve number.

+ve value indicates string1 > string2. 0 indicates string1 and string2 are equal -ve value indicates string1 < string2.

6) strcmpi (string 1, string2):This function is similar to strcmp().The only difference is that it ignores the case. For example, SparK and spark both are the same.

7) strlwr (string):: This function accepts a single string that can be in any case(lower or upper). Itconverts the string in lower case.

8) strupr (string):: This function accepts a single string that can be in any case(lower or upper). It converts the string in the upper case.

What is a string reverse function?

Sometimes it is easier to search a string from the end to the beginning. A reverse string would be useful for debugging, or as an alternate way to write the loop. String reversal as the name suggests reverses the entered string.

If the user enters a string “reverse” as input then it will be changed to “esrever”. strrev() function reverses a given string in C language under the header file string.h.

Note- A string that remains the same even after the reversal is called a palindrome string.

Example: Input: ABCDCBA Reversed string: ABCDCBA. Thus, the given string is a palindrome!

Syntax-
The syntax of strrev() function is

char *strrev(char *string);

Following are the C programming examples we shall go through to reverse a string

  1. Using strrev() function
  2. Reverse String in place (swapping characters)
  3. Using recursion
  4. and Using pointers

Example 1 – Reverse String using strrev()

In this C program, we will use strrev() function to reverse a given string.

#include <stdio.h>
#include <string.h>
int main()
{
   char s[100];

   //taking inputs
   printf("Enter a string to reverse\n");
   gets(s);

   //reversing the string
   strrev(s);

   //printing the string
   printf("Reverse of the string: %s\n", s);

   return 0;
}

Example 2 – Reverse String In-place

Reverse a string in place means swapping characters at the beginning and the end of the string and then move towards the middle of the string. It doesn’t need a separate buffer to hold the reversed string.

In the following C program, we will read a string from the user and reverse this string in place.

#include<stdio.h>
#include<string.h>
int main()
{
char str[100],temp;
int i=0,j=0;
printf("enter string \n");
gets(str);
j=strlen(str)-1;
while(i<j)
{
temp=str[j];
str[j]=str[i];
str[i]=temp;
i++;
j--;
}
printf("\n Reversed string is : ");
puts(str);
return 0;
}

Example 3 – Reverse String using Recursion

The recursive function takes a string as an input and reverses the string until it encounters ‘\0’ by calling the reverse function.

Though the recursive function looks easier, it won’t give better performance than strrev() function because for every recursive call stack will be created.

The overhead of creating a stack whenever a recursive function called will effects its efficiency.
In the following C program, we will use this recursion technique to reverse a string read from the console.

#include<stdio.h>
char* reverse(char* str); // declaring recursive function
void main() {
int i, j, k;
char str[100];
char *rev;
printf("Enter the string:\t");
gets(str);
printf("The original string is:%s \t “,str);
rev = reverse(str);
printf("The reversed string is: ");
puts(rev);
}
char* reverse(char *str) { // defining the function
static int i = 0;
static char rev[100];
if(*str)
{
reverse(str+1);
rev[i++] = *str;
}
return rev;
}

Output:

Enter the string: abcdefghijklmnopqrstuvwxyz
The original string is: abcdefghijklmnopqrstuvwxyz
The reversed string is: zyxwvutsrqponmlkjihgfedcb

Example 4 – Reverse String using Pointers

Another way of accessing a contiguous block of memory, instead of with an array, is with a pointer. Since we are talking about strings, which are made up of characters, we’ll be using pointers to characters i.e char*s .

However, pointers only hold an address, they cannot hold all the characters in a character array. This means that when we use a char * to keep track of a string, the character array containing the string must already exist.

C program to reverse a string using pointers is given below.
In the following C program, we will reverse the given string using String Pointer.

#include<stdio.h>
#include<string.h>
void reverse(char*);
int main() {
char s[100];

printf("Enter a string\n");
gets(s);
reverse(s);
printf("Reverse of the string is \"%s\".\n", s)
return 0;
}

void reverse(char *s) {
int length, c;
char *begin, *end, temp;
length = strlen(s);
begin = s;
end = s;
for (c = 0; c < length - 1; c++)
end++;
for (c = 0; c < length/2; c++) {
temp = *end;     //using pointers
*end = *begin;
*begin = temp;
begin++;
end--;
}
}

Conclusion

Hope you learned something through our post on String Reverse Function in C. Happy Coding!

Sliding window techniqueDynammic programming are also an important topics which you must refer!

Leave a Comment

Your email address will not be published. Required fields are marked *