用C语言写下题:有一个前中后都有空格的字符串 删除其前面所有的空格,其余的空格不要删除
时间: 2023-11-27 18:54:24 浏览: 74
```c
#include <stdio.h>
#include <string.h>
void removeLeadingSpaces(char *str) {
int i, j = 0, len = strlen(str);
for (i = 0; i < len; i++) {
if (str[i] != ' ') {
break;
}
}
for (; i < len; i++) {
str[j++] = str[i];
}
str[j] = '\0';
}
int main() {
char str[] = " This is a test string. ";
printf("Before: \"%s\"\n", str);
removeLeadingSpaces(str);
printf("After: \"%s\"\n", str);
return 0;
}
```
输出:
```
Before: " This is a test string. "
After: "This is a test string. "
```
相关问题
c语言:有一个前中后都有空格的字符串,删除其前面的所有空格,中间和后面的空格不要删除
可以使用C语言中的指针和数组来删除前面的空格。具体实现如下:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = " Hello world! ";
char *ptr = str; // 定义指向字符串的指针
// 去掉前面的空格
while (*ptr == ' ') {
ptr++;
}
// 输出去掉前面空格后的字符串
printf("%s\n", ptr);
return 0;
}
```
运行结果为:
```
Hello world!
```
可以看到,输出的字符串去掉了前面的空格,而中间和后面的空格没有被删除。
c语言实现:有一个前中后都有空格的字符串,删除其前面的所有空格,中间和后面的空格不要删除。
可以使用指针来实现字符串的操作,具体实现如下:
```c
#include <stdio.h>
#include <string.h>
void remove_front_spaces(char* str)
{
if (str == NULL) {
return;
}
char* p = str;
char* q = str;
// 找到第一个非空格字符
while (*p == ' ') {
p++;
}
// 移动字符串
while (*p != '\0') {
*q++ = *p++;
}
*q = '\0';
}
int main()
{
char str[] = " hello world ";
printf("Before: [%s]\n", str);
remove_front_spaces(str);
printf("After: [%s]\n", str);
return 0;
}
```
输出结果为:
```bash
Before: [ hello world ]
After: [hello world ]
```
在函数 `remove_front_spaces` 中,首先找到第一个非空格字符,然后将其后的字符串复制到原始字符串的开头。由于我们只删除前面的空格,所以中间和后面的空格不会被删除。最后,我们在原始字符串的末尾添加了一个空字符,以确保字符串的完整性。