给定字符串str,任务是在C中交换此字符串的相邻字符。
例子:
Input: str = "geeks"
Output: NA
Not possible as the string length is odd
Input: str = "geek"
Output: egke
方法:
- 检查字符串的长度是偶数还是奇数。
- 如果长度为奇数,则无法进行交换。
- 如果长度是偶数,则将字符串的每个字符一个接一个地替换为相邻的字符。
下面是上述方法的实现:
// C program to swap
// adjacent characters of a String
#include
#include
// Function to swap adjacent characters
void swap(char* str)
{
char c = 0;
int length = 0, i = 0;
// Find the length of the string
length = strlen(str);
// Check if the length of the string
// is even or odd
if (length % 2 == 0) {
// swap the characters with
// the adjacent character
for (i = 0; i < length; i += 2) {
c = str[i];
str[i] = str[i + 1];
str[i + 1] = c;
}
// Print the swapped character string
printf("%s\n", str);
}
else {
// Print NA as the string length is odd
printf("NA\n");
}
}
// Driver code
int main()
{
// Get the string
char str1[] = "Geek";
char str2[] = "Geeks";
swap(str1);
swap(str2);
return 0;
}
输出:
eGke
NA
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。