将字符串当中的单词,按照句子的倒序输出。
// StrInverse.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "malloc.h"
// 2013-10-2 12:02:32 @sonikk neteasy
// calc the length of string (char*)
// implement strlen()
int slen(char * str)
{
int n = 0;
while( *(str++) != '\0')
n++;
return n;
}
void inverseStr(char * str, int len, int start, int end)
{
//printf("str=%s, len=%d", str, len);
int sublen = end - start + 1;
char temp;
for(int i=0; i<sublen/2; i++)
{
temp = str[start + i];
str[start + i] = str[end - i];
str[end - i] = temp;
}
}
void inverseWords(char * str)
{
int len = slen(str);
int start = 0;
int end = 0;
// inverseAll
inverseStr(str, len, 0, len-1);
// maerd a evah I ->
for(int i=0; i < len; i++)
{
if(str[i+1] == ' ' || i == len - 1)
{
end = i;
inverseStr(str, len, start, end);
int k = i + 1;
while( k<len && str[k] == ' ') // k < len &&
{
k++;
}
start = k;
}
}
}
char* mystrcpy(char* str)
{
int len = strlen(str);
char* buf = (char*)malloc( len + 1 );
for(int i=0; i<len; i++)
{
buf[i] = str[i];
}
buf[len] = '\0';
return buf;
}
int _tmain(int argc, _TCHAR* argv[])
{
char* buf0 = "I have a dream"; // 字符串常量(只读)
//char buf[] = "I have a dream"; // 字符串变量
char* buf = mystrcpy(buf0); // 可读可写
// "I have a dream"
printf("[1] buf = %s\n", buf);
inverseWords( buf );
// "dream a have I"
printf("[2] buf = %s\n", buf);
getchar();
return 0;
}