向量字符串中每个单词的反转字符

时间:2015-03-28 22:06:10

标签: c++ string algorithm c++11 vector

vector <string> theWords;
theWords.reserve(100);

istream_iterator <string> stringReader(cin);
istream_iterator <string> stringReaderEOF;

while(stringReader != stringReaderEOF)
    theWords.push_back(* stringReader++);

display(theWords);
//reverse(theWords);

INPUT:

samin khan

输出:

samin

倒车后:

nimas

nahk

如何反转字符?

2 个答案:

答案 0 :(得分:1)

此代码将反转vector<string>

的所有字符串元素
#include <string> 
#include <algorithm>

void main()
{
    vector<string> a = { "abc", "pqr", "xyz" };
    for (auto& s : a)
    {
        reverse(begin(s), end(s));
    }
}

答案 1 :(得分:0)

void reverse(string& s)
{
    int i = 0, j = s.length() - 1;
    while(i < j)
    {
        swap(s[i++], s[j--]);
    }
    cout << s << endl;
}

在main()中:

reverse(theWords[0]);
reverse(theWords[1]);
//.....