zoukankan      html  css  js  c++  java
  • 字符串反转——按字符&按字

    1.字符串按字节反转,即字符串abcdef,反转为fedcba。

    #include <iostream>
    using namespace std;
    
    char *reverse(char *str)
    {
        if(NULL==str)
            return NULL;
    
        char *begin=str;
        char *end=str;
        
        while(*end!='\0')//让end指向最后一个字符
            end++;
        end--;
        while(begin<end)
        {
            char tmp=*begin;
            *begin=*end;
            *end=tmp;    
            begin++;//注意!指针移动!
            end--;
        }
        return str;
    }
    int main()
    {
        char s[]="abcdefg";
        char *p=reverse(s);
        cout<<p<<endl;
        return 0;
    }

    2.字符串按字反转,即字符串"how are you",反转为"you are how"。

    方法一:

    #include <iostream>
    using namespace std;
    
    void Reverse(char *begin,char *end)
    {
        if(NULL==begin||NULL==end)
            return;
        while(begin<end)
        {
            char tmp=*begin;
            *begin=*end;
            *end=tmp;
            
            begin++;//不要忘了!
            end--;
        }
        
    }
    
    char *ReversSentence(char *str)
    {    
        if(NULL==str)
            return NULL;
        //将整个字符串按字节反转    
        char *pBegin=str;
        char *pEnd=str;
        while(*pEnd!='\0')
            pEnd++;
        pEnd--;
        Reverse(pBegin,pEnd);
        //将每个字反转
        //pBegin=str;
        pEnd=str;
        while(*pBegin!='\0')
        {
            if(*pBegin==' ')//if和else if 这两个条件的顺序不能颠倒。
            {
                pBegin++;
                pEnd++;
                continue;
            }
            else if(*pEnd==' '||*pEnd=='\0')
            {    
                Reverse(pBegin,--pEnd);//此时pEnd指向某个字的最后一个字符
                pBegin=++pEnd;//此时pBegin指向' '空格的下一个字符
            }
             
            else    
                pEnd++;
        }
        
        return str;
    }
    int main()
    {
        char s[]="how are you";
        char *p=ReversSentence(s);
        cout<<p<<endl;
        return 0;
    }

    方法二:http://blog.csdn.net/jianxiong8814/article/details/1595110

  • 相关阅读:
    什么是webview
    juqery.fn.extend和jquery.extend
    LeetCode
    5. Longest Palindromic Substring
    42. Trapping Rain Water
    11. Container With Most Water
    621. Task Scheduler
    49. Group Anagrams
    739. Daily Temperatures
    3. Longest Substring Without Repeating Characters
  • 原文地址:https://www.cnblogs.com/fly1988happy/p/2703557.html
Copyright © 2011-2022 走看看