题目要求按单词反转字符串,并且删除字符串开始和结尾处的空格,以及如果单词间空格大于一个的话,将其缩减为一个。如果输入是“ ”则输出为“”。题目类型是easy,就不赘述了,直接贴代码吧。
#include
#include
#include
void reverseword(char *strr);
void reverseword(char *st)
{
//printf("%s",strr);
//printf("\n");
//
char *p, *q, *ini, *sta;
char temp;
ini = sta = st;
while (*st == ' ')
{
st++;
}
p = q = st;
while (*q != '\0')
{
q++;
}
q--;
while (p <= q)
{
temp = *p;
*p = *q;
*q = temp;
p++;
q--;
}//反转整个字符串
//printf("%s",test);
//printf("\n");
while (*st == ' ')
{
st++;
}
// strr = test;
char *s;
q = p = s = ini;//指针指向开始位置
while (*st != '\0')
{
*ini = *st;
ini++;
st++;
}
*ini = *st;
while (*q != '\0')
{
if (*q == ' ' || *(q + 1) == '\0')
{
p--;
if (*(q + 1) == '\0')//处理最后一个字串
p++;
while (s <= p)
{
temp = *p;
*p = *s;
*s = temp;
s++;
p--;
}//反转局部字符串
s = q + 1;
p = q;
}
q++;
p++;
}
p = q = sta; //处理单词之间大于一个的空格,将他们之间的空格缩减为一个
while (*sta != '\0')
{
sta++;
if (*sta == ' ')
{
p = sta + 1;
q = p;
while (*q == ' ')
{
q++;
}
while (*q != '\0')
{
*p = *q;
p++;
q++;
}
*p = *q;
}
}
//printf("%s stop",strr);
//printf("\n");
//system("pause");
}
void main()
{
char strri[]= " a b ";
printf("%s", strri);
printf("\n");
char *st = strri;
reverseword(st);
printf("%s stop", st);
printf("\n");
system("pause");
}
#include
#include
void reverseword(char *strr);
void reverseword(char *st)
{
//printf("%s",strr);
//printf("\n");
//
char *p, *q, *ini, *sta;
char temp;
ini = sta = st;
while (*st == ' ')
{
st++;
}
p = q = st;
while (*q != '\0')
{
q++;
}
q--;
while (p <= q)
{
temp = *p;
*p = *q;
*q = temp;
p++;
q--;
}//反转整个字符串
//printf("%s",test);
//printf("\n");
while (*st == ' ')
{
st++;
}
// strr = test;
char *s;
q = p = s = ini;//指针指向开始位置
while (*st != '\0')
{
*ini = *st;
ini++;
st++;
}
*ini = *st;
while (*q != '\0')
{
if (*q == ' ' || *(q + 1) == '\0')
{
p--;
if (*(q + 1) == '\0')//处理最后一个字串
p++;
while (s <= p)
{
temp = *p;
*p = *s;
*s = temp;
s++;
p--;
}//反转局部字符串
s = q + 1;
p = q;
}
q++;
p++;
}
p = q = sta; //处理单词之间大于一个的空格,将他们之间的空格缩减为一个
while (*sta != '\0')
{
sta++;
if (*sta == ' ')
{
p = sta + 1;
q = p;
while (*q == ' ')
{
q++;
}
while (*q != '\0')
{
*p = *q;
p++;
q++;
}
*p = *q;
}
}
//printf("%s stop",strr);
//printf("\n");
//system("pause");
}
void main()
{
char strri[]= " a b ";
printf("%s", strri);
printf("\n");
char *st = strri;
reverseword(st);
printf("%s stop", st);
printf("\n");
system("pause");
}