C - Reverse the String without using strrev() function and temporary string in C programming.


IncludeHelp 05 September 2016

In this code snippet/program/example we will learn how to reverse the string without using any library function (strrev()) and another temporary string?

In this program we are reversing the string by calculating length (without using strlen()) and by swapping characters of the string.

C Code Snippet - Reverse String in C without using strrev() Library function and Temporary String

/*C - Reverse the String without using 
strrev() function in C programming.*/

#include <stdio.h>

//function to calculate length of string
short getStrLen(char* s){
	short len=0;
	while(s[len]!='\0')
	    len++;
	    
    return len;
}

///function to reverse the string
void reverseString(char *str){
	short len=0,i,j;
	char temp; //temp character
	//get length of  string
	len=getStrLen(str);
	
	//reverse string
	for(i=len-1,j=0;j<(len/2); i--,j++){
		//swap characters
		temp=str[j];
		str[j]=str[i];
		str[i]=temp;
	}			
}
int main(){
	char text[100]={0};
	
	printf("Enter string: ");
	//scanf("%s",text); //this is for without space
	scanf ("%[^\n]%*c", text);
	
	printf("String before reverse: %s\n",text);
	//reverse string
	reverseString(text);
	printf("String after reverse: %s\n",text);
	
	return 0;
}

    First Run (with Odd number of characters):
    Enter string: Hello 
    String before reverse: Hello
    String after reverse: olleH 

    First Run (with Even number of characters):
    Enter string: Hello World!
    String before reverse: Hello World! 
    String after reverse: !dlroW olleH 



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.