|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include <stdio.h>
#include <string.h>
#define MAX 21 // 包含结束符就是21个字符
int main()
{
int ch, space, i = 0;
char str[MAX];
space = MAX - 1;
printf("请输入一行文本:");
while ((ch = getchar()) != '\n')
{
str[i++] = ch;
if (i == MAX - 1)
{
break; // 到了字符数组最后一个位置
}
if (ch == ' ')
{
space = i; // 记录最后一个空格的位置
}
}
if (i >= MAX - 1)
{
str[space] = '\0';
}
else
{
str[i] = '\0';
}
printf("你输入的文本是:%s\n", str);
return 0;
}
while循环结束以后的i》=MAX-1是否可以换成i==MAX-1即可?因为我认为i再怎么样也不可能大于MAX-1
没错,i 的值不可能大于 MAX - 1。
下面是我写的代码,可以同时去掉位于字符串前后的 TAB 字符和空格字符。
- #include <stdio.h>
- #define MAX 21 // 包含结束符就是21个字符
- int main()
- {
- char c , str[MAX] ;
- int e , k , m ;
- printf("请输入一行文本:") ;
- for(m = 0 ;(c = getchar()) != '\n' && m < MAX - 1 ; str[m ++] = c) ;
- for(; (str[m - 1] == 0x09 || str[m - 1] == 0x20) && m > 0 ; str[m -- - 1] = 0) ;
- for(e = 0 ; (str[e] == 0x09 || str[e] == 0x20) && e < m ; e ++) ;
- for(k = e ; k < m + 1 ; k ++) str[k - e] = str[k] ;
- printf("你输入的文本是:%s\n", str) ;
- }
复制代码
|
|