21xrx.com
2024-11-22 08:11:04 Friday
登录
文章检索 我的文章 写文章
C程序反转字符串中的单词
2021-07-08 09:06:37 深夜i     --     --
C

C 程序来反转字符串或句子中的单词,例如,如果输入字符串是“c++ programming language”,那么输出将是“++c gnimmargorp egaugnal”,即我们将反转输入字符串中出现的每个单词。 算法非常简单,只需扫描字符串并继续存储字符,直到出现空格。 如果找到一个空格,那么我们就找到了一个单词,所以我们附加空终止符,然后将单词反转,然后将原始字符串的字符与反转获得的字符串一起复制。 然后重复上一步直到字符串结束。

C程序

#include <stdio.h>
#include <string.h>


void reverse_string(char*);
void reverse_words(char*);

int main() {
  char a[100];

  gets(a);

  reverse_words(a);

  printf("%s\n", a);

  return 0;
}

void reverse_words(char *s) {
  char b[100], *t, *z;
  int c = 0;

  t = s;

  while(*t) {                           //processing complete string
    while(*t != ' ' && *t != '\0') {    //extracting word from string
      b[c] = *t;
      t++;
      c++;
    }
    b[c] = '\0';
    c = 0;
 
    reverse_string(b);        // reverse the extracted word

    z = b;

    while (*z) {    //copying the reversed word into original string
      *s = *z;
      z++;
      s++;
    }

    while (*s == ' ') {                 // skipping space(s)
      s++;
    }
    /*
     * You may use if statement in place of while loop if
     * you are assuming only one space between words. If condition is
     * used because null terminator can also occur after a word, in
     * that case we don't want to increment pointer.
     * if (*s == ' ') {
     *   s++;
     * }
     */
    t = s;                              // pointing to next word
  }
}

/*
 * Function to reverse a word.
 */

void reverse_string(char *t) {
  int l, c;
  char *e, s;

  l = strlen(t);
  e = t + l - 1;

  for (c = 0; c < l/2; c++) {
    s  = *t;
    *t = *e;
    *e = s;
    t++;
    e--;
  }
}

下载反向单词程序。

程序输出:

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复