Topic One: Problem Description:
Enter an English sentence to flip the order of the words in the sentence, but the order of the characters within the word does not change. For simplicity, punctuation is handled like normal characters. such as the input string "I am a student." Output string "student. A am I ". Problem Analysis:
This topic is relatively simple, flip two times string can be. Flips the whole string for the first time and flips the individual word for the second time. Of course, two order can be reversed ~ ~ To achieve a relatively simple, mainly is the flip function. Code implementation:
#include <iostream> using namespace std;
#include <cassert> void Reverseword (char* begin, char* end) {assert (begin && end);
while (begin < end) {char tmp = *begin;
*begin = *end;
*end = tmp;
begin++;
end--;
} void Reversesentence (char* str,int len) {assert (str);
char* start = str;
char* end = str;
Reverseword (Start, str + len-1);
while (*end!= ' ") {while (*end!= ' && *end '") {
++end;
}//encountered a space or a string ending Reverseword (start, end-1);
if (*end!= ' ") {start = end + 1;
end = start;
int main () {char str[] = "I am a student";
Reversesentence (str,sizeof (str)/sizeof (str[0])-1);
cout << str << Endl;
System ("pause"); REturn 0;
}
Topic Two: Question description:
The left rotation of a string moves the character at the front of the string to the tail of the string. Define a function that implements a string left rotation operation. For example, the input string "ABCDEFG" and the number 2, the output "Cdefgab". Problem Analysis:
With the foundation of one of the above topics, this topic is still rotating, rotating the whole and rotating parts. Just like the last question, rotate the entire string and rotate each word, and the topic is to rotate the entire string, then rotate the first n characters and the remaining n characters that need to move left, and you can still call the Reverseword () function above. Code implementation:
#include <iostream>
using namespace std;
#include <cassert>
//L-
void Reverseword (char* begin, char* end)
{
assert (begin && End) ;
while (begin < End)
{
char tmp = *begin;
*begin = *end;
*end = tmp;
begin++;
end--
}
}
void Leftrotate (char* str, int n)
{
assert (str);
int len = strlen (str);
if (n < len && n > 0 && len > 0)
{
//Flip First n
reverseword (str, str + n-1);
Flip behind the character
Reverseword (str + n, str + len-1);
Flip
The overall reverseword (str, str + len-1)
;
}
int main ()
{
char str[] = "abcdef";
Leftrotate (str,2);
cout << str << endl;
System ("pause");
return 0;
}
Today's topic on the analysis to here ~ finally still want to wish you a happy New Year ~ Hope oneself in the new year to put down not belong to their own people or things ~ to become a better self ~ ~