- 字符串翻转,给定一个字符串,逐个翻转字符串中每个单词,
例如,输入“the sky is blue”,输出“blue is sky the”。 - 要区分空格和结尾的情况
#include
#include
#include
void str_reverse(char* src)
{
char* rev = (char*)malloc(strlen(src) + 1);
int len = strlen(src);
int i, j,left = 0, dst_pos;
for (i = 0; i <= len; i++)
{
if(src[i] == ' ' || src[i]== '\0')
{
dst_pos = len - i;
for (j = left; j < i; j++)
{
rev[dst_pos] = src[j];
dst_pos++;
}
if (left==0)
rev[dst_pos] = '\0';
else
rev[dst_pos] = ' ';
left = i + 1;
}
}
int k = 0;
while (rev[k] != '\0') {
src[k] = rev[k];
k++;
}
}
int main()
{
char src[] = "the sky is blue";
printf("The outis:%s\n", src);
str_reverse(src);
printf("The outis:%s\n", src);
return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
#include
#include
#include
using namespace std;
void Str_Reverse(string& Src)
{
vector<string> vec_Src;
for(int i=0;i< Src.size();i++)
{
string temp_str = "";
while (Src[i] != ' ' && Src[i] != '\0')
{
temp_str.push_back(Src[i]);
i++;
}
vec_Src.push_back(temp_str);
temp_str.clear();
}
Src.clear();
for(int j = vec_Src.size() - 1;j >= 0; j--)
{
if (j == 0) Src += vec_Src[j];
else Src += vec_Src[j] + " ";
}
}
int main()
{
string src = "the sky is blue";
cout << src << endl;
Str_Reverse(src);
cout << src << endl;
return 0;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35