c语言用指针统计字符
时间: 2024-03-03 08:44:31 浏览: 14
以下是使用指针统计字符的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
char c[80];
char *k = c;
int m = 0, x = 0, n = 0, p 0, q = 0;
gets(c);
while (*k != '\0') {
if (*k >= 'A' && *k <= 'Z') m++;
else if (*k >= 'a' && *k <= 'z') x++;
else if (*k == ' ' || *k == '\t') n++;
else if (*k >= '0' && *k <= '9') p++;
else q++;
k++;
}
printf("%d %d %d %d %d", m, x, n, p, q);
return 0;
}
```
相关问题
用指针统计字符串长度c语言
以下是用指针统计字符串长度的C语言代码:
```c
#include <stdio.h>
int My_strlen(char *src) {
int len = 0;
while(*src++ != '\0') {
len++;
}
return len;
}
int main() {
char *str = "abcde";
int len = My_strlen(str);
printf("%d\n",len);
getchar();
return 0;
}
```
该代码中,`My_strlen`函数使用指针遍历字符串,每遍历一个字符,就将长度加1,直到遍历到字符串的结尾符`\0`。在`main`函数中,我们定义了一个字符串指针`str`,并将其指向字符串常量"abcde"的首地址。然后,我们调用`My_strlen`函数,将`str`作为参数传入,函数返回字符串的长度,最后在屏幕上输出字符串的长度。
c语言使用指针实现字符串反转
下面是使用指针实现字符串反转的C语言代码:
```c
#include <stdio.h>
#include <string.h>
void reverseString(char* str) {
int len = strlen(str);
char* start = str;
char* end = str + len - 1;
while (start < end) {
char temp = *start;
*start = *end;
*end = temp;
start++;
end--;
}
}
int main() {
char str[] = "hello world";
reverseString(str);
printf("%s\n", str); // 输出 "dlrow olleh"
return 0;
}
```
在函数`reverseString()`中,我们首先获取字符串的长度。然后,我们使用两个指针`start`和`end`来分别指向字符串的开头和结尾。接下来,我们使用一个`while`循环来交换`start`和`end`所指向的字符,直到它们相遇为止。最终,字符串就被反转了。