[编程题目]翻转一句话中单词出现的先后顺序

[编程题目]翻转一句话中单词出现的先后顺序
example: “This is a beautiful city” === > “city beautiful a is This”

#include "stdlib.h"
#include "stdio.h"
#include "string.h"
#include "stdint.h"
#include "assert.h"

/*reverse string*/
void reverse(char* start, char* end) 
{
	char swap = 0;
	char* ch = start;
	printf("before :%s\n",ch);
	while(start < end) {
		swap = *end;
		*end = *start;
		*start = swap;
		start++;
		end--;
	}
	printf("after :%s\n",ch);
	return;
}

int get_word_range(char** string, char**word_start, char** word_end)
{
	char* str = *string;
	while(str && *str != 0 && *str == ' ') {
		str++;
	} 
	if(NULL == str || (*str == 0)) {
		return -1;
	}
	*word_start = str;
	while(*str && *str != 0 && *str != ' ') {
		str++;
	}
	*word_end = str-1;
	*string = str;
	printf("start %c, end %c\n",**word_start,**word_end);
	return 0;
}

int main (int argn,char* argv[])
{
#define STRING "This is a beautiful city"
	char* str = 0, *word_start=0, *word_end=0;
	char* original = 0;
	str = malloc(sizeof(STRING));
	strcpy(str,STRING);
	str[strlen(STRING)] = 0;
	original = str;
	printf("the string before reverse : %s\n",original);
	while(0 == get_word_range(&str,&word_start,&word_end)) {
		reverse(word_start,word_end);
	}
	printf("processing :%s\n",original);
	reverse(original,original+strlen(original)-1);
	printf("the string after reverse : %s\n",original);
	free(original);
	return 0;
}

 

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>