Skip to content

Instantly share code, notes, and snippets.

@housemeow
Last active August 29, 2015 13:57
Show Gist options
  • Save housemeow/9827664 to your computer and use it in GitHub Desktop.
Save housemeow/9827664 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void input(char *str);
void reversedString(char *str, char* output);
void reversedSentence(char *sentenceProblem,char *solvedSentenceProblem);
int sentenceLength(char *sentence);
char* getSecondWordPointer(char *sentence);
void getFirstWord(char *sentenceProblem, char *firstWord);
int main()
{
char str[100];
char reversedStr[1000];
input(str);
//reversedString(str, reversedStr);
reversedSentence(str, reversedStr);
printf("%s\n", reversedStr);
system("pause");
return 0;
}
void input(char *str)
{
//scanf("%s", str);
gets(str);
}
void reversedString(char *question, char* output)
{
if(strlen(question)>1){
//general case
//step1: 切割問題
char smallerQuestion[100];
strcpy(smallerQuestion, question+1);
char solvedQuestion[100];
reversedString(smallerQuestion, solvedQuestion);
//step2: 處理問題
strcpy(output, solvedQuestion);
strncat(output, question, 1);
}else{
//解決最小的問題
strcpy(output, question);
}
}
int sentenceLength(char *sentence)
{
char str[1000];
strcpy(str, sentence);
//printf("sentence=%s\n", sentence);
int length = 0;
char * pch;
pch = strtok (str," ");
while (pch != NULL)
{
length++;
pch = strtok (NULL, " ");
}
//printf("length = %d\n", length);
return length;
}
char* getSecondWordPointer(char *sentence)
{
char str[1000];
char * pch;
//str = "hello world";
strcpy(str, sentence);
//str = "hello_world"; _ is \0
//pch = ^
pch = strtok (str," ");
//str = "hello_world"; _ is \0
//pch = ^
pch = strtok (NULL, " ");
size_t offset = pch-str;
return sentence + offset;
}
void getFirstWord(char* sentenceProblem, char* firstWord)
{
char str[1000];
char * pch;
strcpy(str, sentenceProblem);
pch = strtok (str," ");
strcpy(firstWord, pch);
}
void reversedSentence(char *sentenceProblem,char *solvedSentenceProblem)
{
if(sentenceLength(sentenceProblem)>1){
//general case
//step1: 切割問題
char smallerQuestion[100];
strcpy(smallerQuestion, getSecondWordPointer(sentenceProblem));
char solvedQuestion[100];
reversedSentence(smallerQuestion, solvedQuestion);
//step2: 處理問題
strcpy(solvedSentenceProblem, solvedQuestion);
strcat(solvedSentenceProblem, " ");
char firstWord[100];
getFirstWord(sentenceProblem, firstWord);
//printf("sentenceProblem=%s, firstWord=%s\n", sentenceProblem, firstWord);
strcat(solvedSentenceProblem, firstWord);
}else{
//解決最小的問題
strcpy(solvedSentenceProblem, sentenceProblem);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment