zoukankan      html  css  js  c++  java
  • Cracking the Coding Interview Q1.2

    Write code to reverse a C-Style String. (C-String means that “abcd” is represented as five characters, including the null character.

    #include<stdio.h>
    #include<string.h>
    
    /**
     * reverse the string in place.
     */
    void reverse(char* str) {
        if (str == NULL)
            return;
        int n = strlen(str);
        char tmp;
        //be careful: i<n/2, not i<=n/2;
        for (int i = 0; i < n / 2; i++) {
            tmp = str[i];
            str[i] = str[n - 1 - i];
            str[n - 1 - i] = tmp;
        }
        return;
    }
    
    int main() {
        char str[10] = "abcde";
        reverse(str);
        printf("%s
    ", str);
    
    }
    View Code

    Solution:

    void reverse(char *str) {
        char * end = str;
        char tmp;
        if (str) {
            while (*end) {
                ++end;
            }
            --end;
            while (str < end) {
                tmp = *str;
                *str++ = *end;
                *end-- = tmp;
            }
        }
    }
    View Code
  • 相关阅读:
    一些想说的事
    化学离子平衡作业偷懒神器
    solution
    SGU 刷题记
    INT128
    # 字典树的指针写法 1.
    CSP-S2 游记
    Tarjan 【整理】
    HGOI 20191106
    20191101
  • 原文地址:https://www.cnblogs.com/jdflyfly/p/3821660.html
Copyright © 2011-2022 走看看