reverse string Algorithm
For function that manipulate strings, modern object-oriented languages, like c # and Java have immutable strings and return a copy (in newly allocated dynamic memory), while others, like c manipulate the original string unless the programmer copy data to a new string. string functions are used in computer programming languages to manipulate a string or query information about a string (some do both).
//
// Reverse String in C++
//
// The All ▲lgorithms Project
//
// https://allalgorithms.com/strings
// https://github.com/allalgorithms/cpp
//
// Contributed by: Tushar Kanakagiri
// Github: @tusharkanakagiri
//
#include <stdio.h>
/* function prototype for utility function to
reverse a string from begin to end */
void reverse(char *begin, char *end);
/*Function to reverse words*/
void reverseWords(char *s)
{
char *word_begin = s;
char *temp = s; /* temp is for word boundry */
/*STEP 1 of the above algorithm */
while (*temp)
{
temp++;
if (*temp == '\0')
{
reverse(word_begin, temp - 1);
}
else if (*temp == ' ')
{
reverse(word_begin, temp - 1);
word_begin = temp + 1;
}
} /* End of while */
/*STEP 2 of the above algorithm */
reverse(s, temp - 1);
}
/* UTILITY FUNCTIONS */
/*Function to reverse any sequence starting with pointer
begin and ending with pointer end */
void reverse(char *begin, char *end)
{
char temp;
while (begin < end)
{
temp = *begin;
*begin++ = *end;
*end-- = temp;
}
}
/* Driver function to test above functions */
int main()
{
char s[] = ""; //Enter string here
char *temp = s;
reverseWords(s);
printf("%s", s);
getchar();
return 0;
}