C程序 - 改变句子中的字符顺序

时间:2014-11-30 19:27:35

标签: c

我很想得到一些我所拥有的任务的帮助,而我似乎无法得到它。 我需要编写一个函数来改变句子中的char顺序。例: “你好世界”将变成:“olleh dlrow”。 这是我给出的函数原型:

int changeCharOrderInSentence(char table[][MAX_SENTENCE_LENGTH], int numOfSentences, int sentenceToChange)

我不能使用指针,静态var或任何东西。 在每个单词都有空格之后,我该怎么办? 并且函数需要返回一个值..它是什么?我没有得到它,因为该函数只是改变了字符的顺序。 这就是我写的:

  int changeCharOrderInSentence(char table[][MAX_SENTENCE_LENGTH], int numOfSentences, int sentenceToChange)
{
    int i,j,lensentence;
    char temp;
    lensentence=strlen(table[sentenceToChange]);
    while(table[sentenceToChange])// as long as we are not at the end of the chosen sentence-'\0'
    {
        for(i=sentenceToChange;(lensentence)/2;i++)
        {
                temp=table[sentenceToChange][i];
                table[sentenceToChange][i]=table[sentenceToChange][lensentence-1-i];
                table[sentenceToChange][lensentence-1-i]= temp; 
        }

    }



    }
谢谢你:)

3 个答案:

答案 0 :(得分:0)

使用每个单词都以空格结尾查找每个单词的事实,然后在每个单词上使用反转代码。

答案 1 :(得分:0)

这可能有点帮助: -

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

int main() 
{
  char name[30] = "Hello";
  strrev(name);  //This will reverse your single word
  return 0;
}

答案 2 :(得分:0)

有趣的挑战是扭转单词而不是句子(这是OP的代码所做的)。像许多问题一样,将其分解为更简单的子功能。

  1. 调用函数来更改一个感兴趣的句子。

    int changeCharOrderInSentence1(char sentence[MAX_SENTENCE_LENGTH]);
    
    int changeCharOrderInSentence(char table[][MAX_SENTENCE_LENGTH], 
        int numOfSentences, int sentenceToChange) {
      if (sentenceToChange < numOfSentences) {
        return changeCharOrderInSentence1(table[sentenceToChange]);
      }
      return 0;
    }
    
  2. 定义changeCharOrderInSentence1()

    void reverse_word(char sentence[], int i, int j);
    
    int changeCharOrderInSentence1(char sentence[MAX_SENTENCE_LENGTH]) {
      int i=0;
      int count = 0;
      do {
        while (sentence[i] == ' ') i++;
        int j = i;
        while (sentence[j] != ' ' && sentence[j] != 0) j++;
        reverse_word(sentence, i, j);
        i = j;
        count++;
      } while (sentence[i] != 0);
      return count;
    }
    
  3. 定义reverse_word()

    void reverse_word(char sentence[], int i, int j) {
      while (j > i) {
        j--;
        char t = sentence[i];
        sentence[i] = sentence[j];
        sentence[j] = t;
        i++;
      }
    }    
    
  4. 目前尚不清楚changeCharOrderInSentence()的返回值应该是多少。此代码假定它是反转的单词数。

    我不喜欢MAX_SENTENCE_LENGTH的名称,因为名称暗示字符串的长度,但OP的示例使用它像char数组的大小。