如何在不使用内置函数的情况下反转句子中的单词

时间:2014-02-16 16:24:37

标签: c string

我有一个字符串“这是一个测试”。我想把它反转为“测试一个就是这个”。我们将把一个字符串作为“这是一个测试”。反转后,它应该是“测试一个就是这个”

#include <stdio.h>

char *reverse(char *p);
void main() {
    char p[100] = "this is a test";
    char *s = reverse(p);
    printf("%s", s);
}

输出 - 测试a就是这个。

6 个答案:

答案 0 :(得分:1)

我会这样做:

#include <boost/regex.hpp>
#include <iostream>
#include <string>

using namespace std;

int main(int argc, char*argv[]){
    string xStr;
    cin >> xStr;

    boost::regex xRegEx("(\\S+)");
    vector<string> words;

    boost::sregex_iterator xIt(xStr.begin(), xStr.end(), xRegEx);
    boost::sregex_iterator xInvalidIt;
    while(xIt != xInvalidIt)
        words.push_back( *xIt++ );

    for(std::vector<string>::iterator it = words.rbegin(); it != words.rend(); ++it) {
        cout << *it << " ";
    }

    return 0;
}

答案 1 :(得分:1)

您可以使用以下算法:

  1. 将字符串拆分为字符串数组中的单词(假设为A)。
  2. 按相反顺序打印A.

答案 2 :(得分:1)

这是一个简单的策略来反转字符串中单词的顺序。

  • 反转字符串(句子)
  • 反转字符串中的每个单词

让我们将任务分解为以下功能:

int mystrlen(char *s);  // find the length of the string
char *rev_substr(char *s, int len);  // reverse the substring s of length len 
char *rev_sentence(char *s);  // reverse the order of words in the string s

以下是函数定义:

int mystrlen(char *s) {
    int i = 0;
    while(*s) {
        i++;
        s++;
    }
    return i;
}

char *rev_substr(char *s, int len) {
    int i = 0; 
    int j = len - 1;
    char temp;
    while(i < j) {
        temp = s[i];
        s[i] = s[j];
        s[j] = temp;
        i++;
        j--;
    }
    return s;
}

char *rev_sentence(char *s) {
    int i, j = 0;
    int len = mystrlen(s);
    rev_substr(s, len);  // reverse the whole string
    for(i = 0; i <= len; i++) {
        // a word is delimited by a space or the null character
        if(s[i] == ' ' || s[i] == '\0') {   
            rev_substr(s+j, i-j);  // reverse back each word
            j = i + 1;    // j is the index of the first letter of the next word
        }
    }
    return s;
}

示例实施:

int main(void) {
    char s[] = "this is a test";
    printf("%s\n", rev_sentence(s));
    return 0;
}

答案 3 :(得分:0)

一种方法是使用字符串流拆分句子,然后只按相反顺序复制字词:

std::string get_reversed( const std::string& str )
{
    std::stringstream input( ss );
    std::vector<std::string> temp;
    std::stringstream output;

    std::copy( std::istream_iterator<std::string>( input , " " ) ,        
               std::istream_iterator<std::string>() ,
               std::back_inserter( temp )
             );

    std::reverse_copy( std::begin( temp ) ,
                       std::end( temp ) ,
                       std::ostream_iterator<std::string>( output , " " )
                     );

    return output.str();        
}

没有正则表达式,没有Boost:只有标准库容器和算法;)

答案 4 :(得分:0)

试试这个:

#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;

char* reverseString(char* inStr)
{
    int numChars = strlen(inStr);             // Length of input string
    char* outStr = (char*)malloc(numChars+1); // Allocate 1 + string length so there is space to fit '\0' 
    char* wordStart = &inStr[numChars];       // Pointer to the start of a word. Initialized to '\0' character of the input
    char* wordEnd = wordStart-1;              // Pointer to the end of word. Initialized to the last character of the input
    char* destination = outStr;               // Pointer to the start of a new word in the reversed string
    char* srcStart;                           // Temporary pointer
    char  delimiter;                          // Word delimiter set to '\0' when the first word of input is copied, set to ' ' for 
                                              // all other words in the input string 
    while (--wordStart >= inStr)
    {
        if (*wordStart == ' ')
        {
            srcStart = wordStart+1;           // start at the first letter following the space    
            delimiter = ' ';                  // add a space at the end of the copied word
        }
        else if (wordStart == inStr)
        {
            srcStart = wordStart;             // start at the first letter of the input string
            delimiter = '\0';                 // add the null terminator to mark the end of the string 
        }
        else
        {
            srcStart = NULL;                  // not at word boundary, mark NULL so the logic below skips the copy operation
        }

        if (srcStart)
        { 
            for (char* src = srcStart; src <= wordEnd; ++src, ++destination)
            {
                *destination = *src;
            }
            *destination = delimiter;
            destination++;
            wordEnd = wordStart-1;
        }
    }

    return outStr;
}

int main(int argc, char** argv)
{
    if (argc < 2)
    {
        cout << "Please provide an input string!..." << endl;
        return -1;
    }
    cout << "Original String = " << argv[1] << endl
         << "Reversed String = " << reverseString(argv[1]) << endl;

    return 0;   
}

这会产生创建新字符串的成本,因此它不是最有效的路径,但它可以完成工作。

答案 5 :(得分:0)

使用递归调用的程序。

int count=0;
void w_rev(char *p)
{
    if((*p)!= '\0')
    {
        if((*p) !=' ')
        {
            w_rev(p+1);
            printf("%c",*p);
        }
        count++;
    }
}
void w_rev_call(char * p)
{
    while(*(p+count) != '\0'  )
        {
            w_rev(p+count);
            printf(" ");
        }
}

如果arr是数组的名称,则语句w_rev_call(arr)将提供所需的输出。