给定一个字符串,任务是使用指针反转此字符串。
例子:
Input: Geeks
Output: skeeG
Input: GeeksForGeeks
Output: skeeGroFskeeG
方法:该方法包括服用两个指针,一个字符串的开始,另一个在字符串的结束点。然后,在这两个指针的帮助下,将字符一一反转。
程序:
#include
#include
// Function to reverse the string
// using pointers
void reverseString(char* str)
{
int l, i;
char *begin_ptr, *end_ptr, ch;
// Get the length of the string
l = strlen(str);
// Set the begin_ptr and end_ptr
// initially to start of string
begin_ptr = str;
end_ptr = str;
// Move the end_ptr to the last character
for (i = 0; i < l - 1; i++)
end_ptr++;
// Swap the char from start and end
// index using begin_ptr and end_ptr
for (i = 0; i < l / 2; i++) {
// swap character
ch = *end_ptr;
*end_ptr = *begin_ptr;
*begin_ptr = ch;
// update pointers positions
begin_ptr++;
end_ptr--;
}
}
// Driver code
int main()
{
// Get the string
char str[100] = "GeeksForGeeks";
printf("Enter a string: %s\n", str);
// Reverse the string
reverseString(str);
// Print the result
printf("Reverse of the string: %s\n", str);
return 0;
}
输出:
Enter a string: GeeksForGeeks
Reverse of the string: skeeGroFskeeG
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。