📌  相关文章
📜  程序在C ++中反转给定字符串中的单词

📅  最后修改于: 2021-05-31 18:48:28             🧑  作者: Mango

给定一个字符串str形式的句子,任务是用C++反转给定句子的每个单词。

例子:

方法1:使用STL函数

  1. 使用STL函数reverse()反转给定的字符串str
  2. 迭代反转的字符串,只要找到空格,就使用STL函数reverse()将该空格之前的单词反转

下面是上述方法的实现:

// C++ program for the above approach
  
#include 
using namespace std;
  
// Function to reverse the given string
string reverseString(string str)
{
  
    // Reverse str using inbuilt function
    reverse(str.begin(), str.end());
  
    // Add space at the end so that the
    // last word is also reversed
    str.insert(str.end(), ' ');
  
    int n = str.length();
  
    int j = 0;
  
    // Find spaces and reverse all words
    // before that
    for (int i = 0; i < n; i++) {
  
        // If a space is encountered
        if (str[i] == ' ') {
            reverse(str.begin() + j,
                    str.begin() + i);
  
            // Update the starting index
            // for next word to reverse
            j = i + 1;
        }
    }
  
    // Remove spaces from the end of the
    // word that we appended
    str.pop_back();
  
    // Return the reversed string
    return str;
}
  
// Driver code
int main()
{
    string str = "I like this code";
  
    // Function call
    string rev = reverseString(str);
  
    // Print the reversed string
    cout << rev;
    return 0;
}
输出:
code this like I

方法2:不使用内置函数我们可以创建reverse()函数,该函数用于反转给定的字符串。步骤如下:

  1. 初始反转给定字符串str的每个单词。
  2. 现在反转整个字符串以获得所需顺序的结果字符串。

下面是上述方法的实现:

// C++ program for the above approach
  
#include 
using namespace std;
  
// Function used to reverse a string
// from index l to r
void reversed(string& s, int l, int r)
{
  
    while (l < r) {
  
        // Swap characters at l and r
        swap(s[l], s[r]);
        l++;
        r--;
    }
}
  
// Function to reverse the given string
string reverseString(string str)
{
  
    // Add space at the end so that the
    // last word is also reversed
    str.insert(str.end(), ' ');
  
    int n = str.length();
  
    int j = 0;
  
    // Find spaces and reverse all words
    // before that
    for (int i = 0; i < n; i++) {
  
        // If a space is encountered
        if (str[i] == ' ') {
  
            // Function call to our custom
            // reverse function()
            reversed(str, j, i - 1);
  
            // Update the starting index
            // for next word to reverse
            j = i + 1;
        }
    }
  
    // Remove spaces from the end of the
    // word that we appended
    str.pop_back();
  
    // Reverse the whole string
    reversed(str, 0, str.length() - 1);
  
    // Return the reversed string
    return str;
}
  
// Driver code
int main()
{
    string str = "I like this code";
  
    // Function call
    string rev = reverseString(str);
  
    // Print the reversed string
    cout << rev;
    return 0;
}
输出:
code this like I
想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”