设计一个函数反转单词前缀 函数原型: void reversePrefix(char *word, char ch); 如: 输入:abcdefd d 输出:dcbaefd 解释:字符d第一次出现在下标3, 反转从下标0到下标3(含下标3)的这段字符 输入:xyxzxe z 输出:zxyxxe 输入:abcd z 输出:abcd 解释:字符z不在这个字符串中,则原字符串不用翻转,原样输出。此函数要在另个函数之中调用
时间: 2023-12-03 18:47:01 浏览: 52
以下是实现反转单词前缀的函数:
```c
void reversePrefix(char *word, char ch) {
int i, j;
int len = strlen(word);
for (i = 0; i < len; i++) {
if (word[i] == ch) {
for (j = 0; j <= i / 2; j++) {
char temp = word[j];
word[j] = word[i - j];
word[i - j] = temp;
}
break;
}
}
printf("%s\n", word);
}
```
该函数接收一个字符串 `word` 和一个字符 `ch`,并且会在字符串 `word` 中查找第一次出现字符 `ch` 的位置,然后将从字符串开头到该位置(包含该位置)的子串反转。如果字符串中不包含字符 `ch`,则原样输出字符串。
在主函数中调用该函数可以这样写:
```c
int main() {
char word1[] = "abcdefd";
char word2[] = "xyxzxe";
char word3[] = "abcd";
char ch1 = 'd';
char ch2 = 'z';
reversePrefix(word1, ch1); // 输出 dcbaefd
reversePrefix(word2, ch2); // 输出 zxyxxe
reversePrefix(word3, ch2); // 输出 abcd
return 0;
}
```
阅读全文
相关推荐










