C++ - Using loops to Reverse a String With No Library Functions
I have used while loop to find out the length of the string and for loop to reverse the string.
Source Code
bool ReverseString(const char *src, char *dst, int len)
{
const char *p = src;
// count the length
int count = 0;
int i = 0;
while(1)
{
if(p == NULL || *p == '\0' ||
*p == '\t' || *p =='\n' || *p == '\r')
{
count = i;
break;
}
p++;
i++;
}
if(count > len)
{
return false; // Insufficient memory in the destination pointer
}
int k = 0;
for(int j = count - 1; j >= 0; j--)
{
dst[k++] = src[j];
}
dst[k] = '\0';
return true;
}
int main()
{
char src[] = "Kathir";
char dst[32];
ReverseString(src, dst, 32);
std::cout << src << "\n" << dst << "\n";
return 0;
}
Output
Kathir
rihtaK
|