用指针写strrev函数
时间: 2024-02-22 19:57:47 浏览: 31
可以通过以下方式使用指针来实现strrev函数:
```c
#include <stdio.h>
#include <string.h>
void strrev(char *str) {
char *start = str;
char *end = str + strlen(str) - 1;
char temp;
while (start < end) {
temp = *start;
*start = *end;
*end = temp;
start++;
end--;
}
}
int main() {
char str[] = "hello world";
printf("Before reversal: %s\n", str);
strrev(str);
printf("After reversal: %s\n", str);
return 0;
}
```
在上面的代码中,我们使用了两个指针start和end,分别指向字符串的开始和结束。在while循环中,我们交换这两个指针所指向的字符,直到它们相遇或者交错为止。这样,就完成了字符串的翻转。
相关问题
c语言strrev函数的实现不使用指针
可以使用数组来实现字符串反转,不使用指针。具体实现如下:
```c
#include <stdio.h>
#include <string.h>
void strrev(char s[]) {
int len = strlen(s);
char temp;
for (int i = 0; i < len / 2; i++) {
temp = s[i];
s[i] = s[len - i - 1];
s[len - i - 1] = temp;
}
}
int main() {
char s[] = "hello world";
strrev(s);
printf("%s\n", s); // 输出:dlrow olleh
return 0;
}
```
在这个实现中,我们先求出字符串的长度,然后利用循环将字符串前半部分和后半部分依次交换,从而实现字符串反转。
用C语言写出
好的,以下是使用 C 语言实现的代码:
```c
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX_LEN 100
int main() {
char sentence[MAX_LEN];
char *words[MAX_LEN/2];
fgets(sentence, MAX_LEN, stdin);
sentence[strcspn(sentence, "\n")] = '\0'; // 删除 fgets 函数读入的换行符
char *token = strtok(sentence, " ");
int i = 0;
while (token != NULL) {
words[i++] = token;
token = strtok(NULL, " ");
}
for (int j = i-1; j >= 0; j--) {
char *word = words[j];
if (isdigit(*word)) {
printf("%s ", strrev(word));
}
else if (islower(*word)) {
printf("%s ", strupr(strrev(word)));
}
else if (isupper(*word)) {
printf("%s ", strlwr(strrev(word)));
}
}
return 0;
}
```
首先,我们定义了一个字符数组 `sentence` 用于存储读入的句子,以及一个字符指针数组 `words` 用于存储句子中分解出的单词。我们使用 `fgets` 函数读入整行句子,并使用 `strcspn` 函数将读入的换行符替换为字符串结束符 `\0`。
接下来,我们使用 `strtok` 函数将句子分解成单个单词,并将每个单词存储在 `words` 数组中。我们使用 `isdigit` 函数判断单词是否为自然数,并将其倒序输出。使用 `islower` 和 `isupper` 函数判断单词是否为小写和大写英文单词,并分别将其转换为大写或小写后再倒序输出。
最后,我们使用 `printf` 函数输出每个单词,并使用空格分隔。