spa highlight amp false main lag temp break bcd
问题: 对于字符串char* = " abcd efg h"; 要求输出" h efg abcd "; 字符串整体翻转,但是里面每一个单词的顺序不翻转
思想:<1>取得原始字符串的长度,
<2>将字符串第一个出现空格位置的索引记录下来,并且放到一个整形数组里,例如上面的
出现空格的位置分别是0 5 11 那么记录数组int b[j]; b[0]=0 b[1] =5; b[2]=11;
<3>针对每一个空格开始出现的位置,将数组b[j] 逆序输出,例如
" h"输出 "h "
" efg" 输出"efg "
" abcd"输出“abcd "
<4>将上面的输出用strcat拼接起来就是得到的目的字符串
代码如下:
- #include < iostream > #include < string.h >
- using namespace std;
- #define ARRAY_LEN 10
- int main() {
- char * a = " OPKI am test abcdef ";
- int len = strlen(a);
- cout << "original---" << a << "---" << endl;
- cout << "str len is " << len << endl;
- int firstempty = false;
- int b[ARRAY_LEN];
- int j = 0;
- for (int i = 0; i < len; i++) {
- if (i == 0) {
- if (a[i] == ‘‘) {
- b[j] = 0;
- j++;
- firstempty = true;
- }
- }
- int temp = i + 1;
- if (a[i] != ‘‘ && a[temp] == ‘‘) {
- b[j] = temp;
- j++;
- }
- }
- cout << "j is " << j << endl;
- cout << "---change--";
- for (int k = j; k > 0; k--) {
- int tmp = b[k - 1];
- int i = 0;
- bool flag = false;
- while (a[tmp] != ‘\0‘) {
- char ch = a[tmp];
- if (ch != ‘‘) {
- flag = true;
- cout << ch;
- } else {
- if (!flag) {
- i++;
- } else {
- break;
- }
- }
- tmp++;
- }
- for (int t = i; t > 0; t--) {
- cout << ‘‘;
- }
- }
- if (!firstempty) {
- cout << *a;
- while ( * (++a) != ‘‘) cout << *a;
- }
- cout << "---" << endl << "end" << endl;
- return 0;
- }
C语言实现将一个字符串翻转
来源: http://www.bubuko.com/infodetail-2317853.html