c语言去除串首尾的空格
时间: 2023-06-22 12:39:55 浏览: 46
可以用以下代码去除C语言字符串首尾的空格:
```c
#include <stdio.h>
#include <string.h>
#include <ctype.h>
char* trim(char* str)
{
// 去除头部空格
char* ptr = str;
while (isspace(*ptr)) {
ptr++;
}
memmove(str, ptr, strlen(ptr) + 1);
// 去除尾部空格
ptr = str + strlen(str) - 1;
while (ptr >= str && isspace(*ptr)) {
ptr--;
}
*(ptr + 1) = '\0';
return str;
}
int main()
{
char str[] = " hello world ";
printf("Before trim: %s\n", str);
printf("After trim: %s\n", trim(str));
return 0;
}
```
运行结果:
```
Before trim: hello world
After trim: hello world
```
相关问题
c语言第1关:去掉字符串首尾空格
可以使用C语言中的库函数 `isspace()` 和 `strcpy()` 来去掉字符串首尾空格,具体实现如下:
```c
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void trim(char *s) {
char *p = s;
int len = strlen(p);
while (isspace(p[len - 1])) p[--len] = 0;
while (*p && isspace(*p)) ++p, --len;
memmove(s, p, len + 1);
}
int main() {
char s[] = " hello world ";
trim(s);
printf("%s\n", s); // 输出"hello world"
return 0;
}
```
这里的 `trim()` 函数采用了双指针的方式,先去掉字符串尾部的空格,再去掉字符串头部的空格,最后使用 `memmove()` 函数将去掉空格后的子串移动到字符串的开头。
c语言字符串逆序输出空格数字不输出
以下是C语言实现字符串逆序输出空格数字不输出的代码:
```c
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void reverse(char *str) {
int len = strlen(str);
int i, j;
char temp;
for (i = 0, j = len - 1; i < j; i++, j--) {
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
int main() {
char str[100];
int i, j;
printf("请输入一个字符串:");
fgets(str, 100, stdin);
str[strcspn(str, "\n")] = '\0'; // 去掉fgets读入的换行符
reverse(str);
for (i = 0; str[i] != '\0'; i++) {
if (!isspace(str[i]) && !isdigit(str[i])) {
putchar(str[i]);
}
}
printf("\n");
return 0;
}
```
代码说明:
1. `reverse`函数用于将字符串逆序,使用双指针法,将字符串首尾对应位置的字符交换即可。
2. `main`函数中,使用`fgets`函数读入字符串,去掉字符串末尾的换行符。
3. 调用`reverse`函数将字符串逆序。
4. 遍历逆序后的字符串,如果当前字符不是空格也不是数字,则输出该字符。
相关问题: