c实现功能(3)去掉字符串左右的空格

#include <stdio.h>

int main() {
    //去掉右边的字符串空格
	char str[100] = "hello world      ";

	int len = 0;
	while (str[len++]);
	len--;
	//printf("%d\n", len);
	
	
	for (int i = len - 1; i >= 0; i--) {
		if (str[i] != ' ') {
			str[i + 1] = '\0';
			break;
		}
	}

	printf("%s", str);

        return 0;
}
#include <stdio.h>

int main() {
	//去掉左边的空格
	char str[100] = "     hello world";

	//计算空格的数量
	int len = 0;
	while (str[len] == ' ') {
		len++;
	}
	//printf("%d\n", len);

	int i = len;
    
        //实现字符往前挪
	while (str[i]) {
		str[i - len] = str[i];
		i++;
	}
	str[i - len] = 0;

	printf("%s\n", str);
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/hc1151310108/article/details/82862005