首页 > 代码库 > 编程之法----面试和算法心得

编程之法----面试和算法心得

第1章 字符串

  1.1 字符串的旋转

    输入一个英文句子,翻转句子中单词的顺序。要求单词内字符的顺序不变,句子中单词以空格符隔开。为简单起见,标点符号和普通字母一样处理。例如:若输入“I am a student.”,则输出“student. a am I”。

#include <stdio.h>

void ReverseString(char *s, int from, int to);

int main(int argc, const char * argv[]) {
    // insert code here...
    
    char s[] = "I am a student.";
    printf("%s\n", s);   // I am a student.
    
    int from = 0;
    int to = 0;
    
    for (int i = 0; i < sizeof(s); i ++) {
        if (s[i] ==   || s[i] == \0) {
            to = i - 1;
            ReverseString(s, from, to);
            from = i + 1;
        }
    }
    printf("%s\n", s);  // I ma a .tneduts
    
    ReverseString(s, 0, sizeof(s) - 2);
    printf("%s\n", s);   // student. a am I
    
    return 0;
}

void ReverseString(char *s, int from, int to) {
    while (from < to) {
        char t = s[from];
        s[from] = s[to];
        s[to] = t;
        from ++;
        to --;
    }
}

 

编程之法----面试和算法心得