c++语⾔将字符串逆序输出,C++实现string类字符串单词的逆
序输出
c++string类型
利⽤c++实现string类字符串单词的逆序输出,并改变源字符串的⼤⼩写。
#include
#include
#include
using namespace std;
string StringReverseWord(string &s)
{
int len = s.length();
if (len == 0)//空字符串
return s;
int n = 0;
while (s[n++] == ' ')
{
n++;
}
if (n == len)//全部都是空格时
{
s = "";
return s;
}
vector svec;
int first, last;
string s1;
int j = 0;
while (j != len)
{
while (s[j] == ' ')
{
j++;
}
first = j;
j++;
}
while (j != len && s[j] != ' ')
{
j++;
}
last = j - 1;
if (j != len)
{
j++;
}
if (last >= first)
{
s1 = s.substr(first, last - first + 1); svec.push_back(s1);
}
}
string s2 = "";
for (size_t k = svec.size() - 1; k != -1; --k) {
s2 = s2 + " " + svec[k];
}
s = s2.substr(1, s2.length() - 1);
for (int t = 0; t != s.length();++t)
{
if (isupper(s[t]))
s[t] = tolower(s[t]);
else if (islower(s[t]))
{
s[t] = toupper(s[t]);
}
}
int main()
{
string s1 = "I am a student";
string s2 = " Semantic Co-occurrence Paterns"; string s3 = " He is a boy ";
string s4 = " hello ";
string s5 = "";
cout << s1 << endl;
cout << StringReverseWord(s1) << endl;
cout << endl;
cout << s2 << endl;
cout << StringReverseWord(s2) << endl;
cout << endl;
cout << s3 << endl;
cout << StringReverseWord(s3) << endl;
cout << endl;
cout << s4 << endl;
cout << StringReverseWord(s4) << endl;
cout << endl;
cout << s5 << endl;
cout << StringReverseWord(s5) << endl;
cout << endl;
system("pause");
return 0;
}
实验结果如下所⽰:

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。