请教个字符串问题
我欲将 "I like to go to shool "--------> "shool to go to like I "希望帮忙前辈帮帮忙。
[解决办法]
char strTmp[16],strTmp1[8][16],*token = NULL,seps[] = " ";
int j = 0;
strcpy( strTmp, "I like to go to shool " );
token = strtok( strTmp, seps );
while( token != NULL )
{
strcpy( strTmp1[j], token );
token = strtok( NULL, seps );
j++;
}
//显示
for( int i=j-1; i> 0; i-- )
printf( "%s ", strTmp1[i]);
getchar();
return;
[解决办法]
将空格间的子串提取出来放到一个指针数组中,再反向输出指针数组中的内容即可
#include <stdio.h>
#include <string.h>
#define MAX_LEN 256
void RevStr(char * Source)
{
char *SrTemp; //输入参数的备份指针
char *pEnd; //无限循环的中断标志指针
char *cBuff[MAX_LEN]; //提取出来的子串存放地
int cnt = 0; //循环变量
int Num = 0; //记录子串个数
//初始化
for(cnt; cnt < MAX_LEN; cnt++)
{
cBuff[cnt] = NULL;
}
SrTemp = Source;
while(1)
{
pEnd = strstr(SrTemp, " ");//返回第一次出现空格时的指针pEnd
if(0 == pEnd)
{
break; //没有空格时,结束循环
}
//动态分配指针数组
cBuff[Num] = (char*)malloc(strlen(SrTemp) - strlen(pEnd) + 1);
//提取子串
strncpy(cBuff[Num++], SrTemp, strlen(SrTemp) - strlen(pEnd));
while( ' ' == *pEnd)
{
pEnd++; //将当前指针移到非空格的字符前
}
SrTemp = pEnd; //继续循环
}
for(cnt = Num - 1; cnt > = 0; cnt--)
{
//反向输入到Source中
memset(Source, 0, strlen(Source));
strcat(Source, cBuff[cnt]);
//释放指针
free(cBuff[cnt]);
cBuff[cnt] = NULL;
}
return;
}