5.5 面试例题:颠倒单词的出现顺序
请编写一个函数来颠倒单词在字符串里的出现顺序。假设所有单词都以空格为分隔符,标点符号也当作字母来对待。 比如: input: "Do or do not, there is no try." output: "try. no is there not, do or Do" --------------------------- ReverseWords1.c -------------------------------------- #include <stdio.h> #include <stdlib.h> #include <string.h> int reverseWords(char str[]) { //copy the characters of the word free(buffer); int main() {
char str[] = "Do or do not, there is no try."; reverseWords(str); int i; for (i = 0; str[i] != ‘\0‘; i++) { printf("%c", str[i]); } printf("%c", ‘\n‘); return 0; } --------------------------- ReverseWords2.c --------------------------------------
#include <stdlib.h>
#include <stdio.h> #include <string.h> void reverseString(char str[], int start, int end) {
char temp; while (start < end) { // swap character temp = str[start]; str[start] = str[end]; str[end] = temp; //move index towards middle start++; end--; } } void reverseWords(char str[]) {
int start = 0, end = 0, length; length = strlen(str); //reverse entire string reverseString(str, 0, length - 1); while (end < length) { //skip non-word characters if (str[end] != ‘ ‘) { //save position of beginning of word start = end; //scan to next non-word character while (end < length && str[end] != ‘ ‘) { end++; } //back up to end of word end--; //reverse word reverseString(str, start, end); } //advanced to next token end++; } } int main() {
char str[] = "Do or do not, there is no try."; reverseWords(str); int i; for (i = 0; str[i] != ‘\0‘; i++) { printf("%c", str[i]); } printf("%c", ‘\n‘); return 0; } |
|
来自: shaobin0604@1... > 《找工作》