Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 颠倒句子中的单词_C_Arrays - Fatal编程技术网

C 颠倒句子中的单词

C 颠倒句子中的单词,c,arrays,C,Arrays,我目前正在学习K.N.King的C编程:一种现代方法。我已经读完了第8章(数组)的内容,我很想继续读第9章,但我还没有解决每章末尾的所谓“编程项目”。不幸的是,14号。。。烦死我了 编写一个程序,将句子中的单词颠倒过来 提示:使用循环逐个读取字符并将其存储在一维字符数组中。让循环在句点、问号或感叹号(“终止字符”)处停止,该句点保存在单独的char变量中。然后使用第二个循环在数组中向后搜索最后一个单词的开头。打印最后一个单词,然后向后搜索下一个单词。重复此操作,直到到达数组的开头。最后,打印终止

我目前正在学习K.N.King的C编程:一种现代方法。我已经读完了第8章(数组)的内容,我很想继续读第9章,但我还没有解决每章末尾的所谓“编程项目”。不幸的是,14号。。。烦死我了

编写一个程序,将句子中的单词颠倒过来

提示:使用循环逐个读取字符并将其存储在一维字符数组中。让循环在句点、问号或感叹号(“终止字符”)处停止,该句点保存在单独的char变量中。然后使用第二个循环在数组中向后搜索最后一个单词的开头。打印最后一个单词,然后向后搜索下一个单词。重复此操作,直到到达数组的开头。最后,打印终止字符

*/
#include<stdio.h>

int main()
{
int ch;
char sentence[200]; //hard set a limit of 200 character sentence
char word[10] = {'\0','\0','\0','\0','\0','\0','\0','\0','\0'}; //hard set limit of 10 character words
int i = 0; //character position in input
int w = 9; //character position in word
char terminator = '\0';
printf("Enter a sentence:");
   while  ( (ch=getchar()) != '\n' )
       {
       if ( ch == '.' || ch == '?' || ch == '!')
          terminator = ch;
       else
         {
         sentence[i] = ch;
         i++;
         }
//       printf("%d",i);
       }
       sentence[i] = '\0';//set last character to null


    int x;
    for ( x=i ; x >= 0 ; x-- )
        {
           if ( sentence[x] == ' ' )
           {
            printf(" ");//print the space followed by what is in the word buffer/array
//          printf("word length %d ",w);
            printf("%c",word[0]); //probably should have a for loop here
            printf("%c",word[1]);
            printf("%c",word[2]);
            printf("%c",word[3]);
            printf("%c",word[4]);
            printf("%c",word[5]);
            printf("%c",word[6]);
            printf("%c",word[7]);
            printf("%c",word[8]);
            printf("%c",word[9]);
            w = 9 ;
            word[0] = '\0'; //fill the word buffer/array with null
            word[1] = '\0';
            word[2] = '\0';
            word[3] = '\0';
            word[4] = '\0';
            word[5] = '\0';
            word[6] = '\0';
            word[7] = '\0';
            word[8] = '\0';
            word[9] = '\0';
//          printf("\n");
//          printf("sentence position %d ",x);
           }
           else //assign the letters from sentence[] to letters in word[]
           {
            word[w] = sentence[x];
            w--;
//          printf("word length %d ",w);
//          printf("%c",sentence[x]);
           }
         }
//print the first word because im using space to delimit the words unless i have a space at the
//beginning of the sentence the code above will skip the first word inputed
    printf(" ");//print the space followed by what is in the word buffer/array
    printf("%c",word[0]);
    printf("%c",word[1]);
    printf("%c",word[2]);
    printf("%c",word[3]);
    printf("%c",word[4]);
    printf("%c",word[5]);
    printf("%c",word[6]);
    printf("%c",word[7]);
    printf("%c",word[8]);
    printf("%c",word[9]);



if ( terminator != '\0' ) //prints a . ? or ! if it is including in the inputed sentence
    printf("%c",terminator);

    printf("\n");
    printf("\n");
return 0;
我一直在考虑将单词定义为空格之间的字符序列。因此,当到达一个空格时,返回,打印每个字符,直到找到另一个空格。我的第一个版本的程序只打印了第一个单词。它的当前版本只打印其他单词。我已经被困在这两天了,所以任何帮助都是非常感谢的。这是我的代码,以及一个输出示例。希望我已经正确地记录了我的代码。提前谢谢

代码
/*包括标准I/O库*/
#包括
/*定义主要*/
内部主(空){
/**
*声明存储句子的字符数组,以及
*表示光标下当前字符的字符,以及
*终止字符
*/
字符句子[100]={''},c,tc;
/**
*声明循环计数器已初始化为0,增量
*变量以及所读句子的大小
*/
int i=0,j=1,size=0;
/*明白了吗*/
printf(“输入句子:\n”);
对于(c=getchar();(c!='。)&&(c!='!')&&
(c!='?')&&(c!='\n');c=getchar(),i++){
语句[i]=c;/*将当前字符存储在数组中*/
size++;/*增加句子的大小*/
}
tc=c;/*获取终止字符*/
/**
*向后遍历数组,打印每个字符序列
*空间之间
*/
对于(i=99;i>=0;i--){
如果(句子[i]=''){
while(句子[i+j]!=“”){
printf(“%c”,句子[i+j]);
j++;
}
j=1;/*重置增量变量*/
printf(“”;/*打印尾随空间*/
}
}
/**
*删除尾随空格并打印终止字符,
*还有一条新路线
*/
printf(“\b%c\n”,tc);
返回0;/*程序成功执行时返回0*/
}
输出:

将每个单词推到堆栈上,然后从索引0到N-1读取堆栈

要考虑的另一种方法:

you can cage a swallow can't you?
uoy t'nac wollaws a egac nac uoy?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
you t'nac wollaws a egac nac uoy?
^^^
you can't wollaws a egac nac uoy?
    ^^^^^
you can't swallow a egac nac uoy?
          ^^^^^^^
you can't swallow a egac nac uoy?
                  ^
you can't swallow a cage nac uoy?
                    ^^^^
you can't swallow a cage can uoy?
                         ^^^
you can't swallow a cage can you?
                             ^^^
对于每一件你想颠倒的事情(无论是一整句话还是一个词):

  • 找到开始和结束
  • 交换开头和结尾字符
  • “向内”移动一次
  • 一直走到“中间”
  • 由于反转字符串块是一种常见的操作,因此将其设置为自己的函数是有意义的。由于该功能需要完成其工作的唯一信息是:

  • 起始索引
  • 结束索引
  • 你认为函数的参数是什么

    另一个需要反复做的常见事情是“找到”某个东西,无论是空格还是标点符号。您可能需要自己编写,或者如果可以使用库函数,或者需要提示,请查阅:

    man strcspn
    

    这里有一个例子,可以实现我提到的。首先,反转每个单词的位置,然后反转整个字符串。下面是一个
    reverse()
    函数,它使用给定的定界字符反转在位字符串。如果愿意,可以扩展为使用多个分隔符

    char *reverse(char *str, char delim)
    {
      char *end = strchr(str, delim);
      char *ret;
      char tmp;
    
      if (end == NULL)
        end = strchr(str, '\0');
    
      ret = end + 1;
      end--;
    
      while (end > str)
      {
        tmp = *str;
        *str = *end;
        *end = tmp;
    
        end--;
        str++;
      }
    
      return ret;
    }
    
    下面是一个带有一个小示例程序的用例:

    int main(int argc, char **argv)
    {
      char *end = strchr(argv[1], '\0');
      char *str = argv[1];
    
      while (str < end)
        str = reverse(str, ' ');
    
      reverse(argv[1], '\0');
      printf("%s\n", argv[1]);
    
      return 0;
    }
    

    我还没试过。希望能对你有所帮助

    char temp[100];
    int j=0, k=100, l=0;
    for(i=size-1; i>=0; i--){
      if(sentence[i] == ' ' || i == 0){
        if(k-i >= 2){// at least one character
    
          if(i==0) j = 0;
          else j = i+1;
    
          for( l=0; j < k; j++, l++){
             temp[l] = sentence[j];
          }
          temp[l] = '\0';
          printf("%s ",temp);
        }
        k = i;
      }
    }
    printf("\b%c",tc);
    
    chartemp[100];
    int j=0,k=100,l=0;
    对于(i=size-1;i>=0;i--){
    如果(句子[i]=''| i==0){
    如果(k-i>=2){//至少一个字符
    如果(i==0)j=0;
    否则j=i+1;
    对于(l=0;j
    int main()
    {
    已发送字符[50],最后,s;
    整数i,j,长度k,温度b;
    clrsc();
    i=0;
    printf(“输入一个句子:”);
    sent[i]=getchar();
    while(sent[i]!='\n'&&sent[i]!='.&&sent[i]!='?'&&sent[i]!='.)
    {
    发送[++i]=getchar();
    }
    last=sent[i];//存储最后一个字符
    b=i;//字符串的长度
    printf(“句子的反面:”);
    对于(;;)
    {
    k=b-1;//从最后一个位置开始
    温度=k;
    while(发送[k]!=''&&k!=-1)
    k--;
    s=k;//在此处存储空间
    b=s;
    对于(j=b+1;j这是我的答案

    /*编写一个程序,将句子中的单词颠倒过来:

    输入一句话:你能关一只燕子,不是吗

    颠倒句子:你不能吞下笼子,是吗

    提示:使用循环逐个读取字符并将其存储在一维字符数组中

    让循环在句点、问号或感叹号处停止-- (“终止字符”),保存为单独的字符变量

    然后使用第二个循环在数组中向后搜索最后一个单词的开头

    打印最后一个单词,然后向后搜索下一个单词。 重复此操作,直到最终到达数组的开头

    最后打印终止字符

    */
    #include<stdio.h>
    
    int main()
    {
    int ch;
    char sentence[200]; //hard set a limit of 200 character sentence
    char word[10] = {'\0','\0','\0','\0','\0','\0','\0','\0','\0'}; //hard set limit of 10 character words
    int i = 0; //character position in input
    int w = 9; //character position in word
    char terminator = '\0';
    printf("Enter a sentence:");
       while  ( (ch=getchar()) != '\n' )
           {
           if ( ch == '.' || ch == '?' || ch == '!')
              terminator = ch;
           else
             {
             sentence[i] = ch;
             i++;
             }
    //       printf("%d",i);
           }
           sentence[i] = '\0';//set last character to null
    
    
        int x;
        for ( x=i ; x >= 0 ; x-- )
            {
               if ( sentence[x] == ' ' )
               {
                printf(" ");//print the space followed by what is in the word buffer/array
    //          printf("word length %d ",w);
                printf("%c",word[0]); //probably should have a for loop here
                printf("%c",word[1]);
                printf("%c",word[2]);
                printf("%c",word[3]);
                printf("%c",word[4]);
                printf("%c",word[5]);
                printf("%c",word[6]);
                printf("%c",word[7]);
                printf("%c",word[8]);
                printf("%c",word[9]);
                w = 9 ;
                word[0] = '\0'; //fill the word buffer/array with null
                word[1] = '\0';
                word[2] = '\0';
                word[3] = '\0';
                word[4] = '\0';
                word[5] = '\0';
                word[6] = '\0';
                word[7] = '\0';
                word[8] = '\0';
                word[9] = '\0';
    //          printf("\n");
    //          printf("sentence position %d ",x);
               }
               else //assign the letters from sentence[] to letters in word[]
               {
                word[w] = sentence[x];
                w--;
    //          printf("word length %d ",w);
    //          printf("%c",sentence[x]);
               }
             }
    //print the first word because im using space to delimit the words unless i have a space at the
    //beginning of the sentence the code above will skip the first word inputed
        printf(" ");//print the space followed by what is in the word buffer/array
        printf("%c",word[0]);
        printf("%c",word[1]);
        printf("%c",word[2]);
        printf("%c",word[3]);
        printf("%c",word[4]);
        printf("%c",word[5]);
        printf("%c",word[6]);
        printf("%c",word[7]);
        printf("%c",word[8]);
        printf("%c",word[9]);
    
    
    
    if ( terminator != '\0' ) //prints a . ? or ! if it is including in the inputed sentence
        printf("%c",terminator);
    
        printf("\n");
        printf("\n");
    return 0;
    
    */
    #包括
    int main()
    {
    int-ch;
    字符句子[200];//硬设置200字符句子的限制
    字符字[10]
    
    char temp[100];
    int j=0, k=100, l=0;
    for(i=size-1; i>=0; i--){
      if(sentence[i] == ' ' || i == 0){
        if(k-i >= 2){// at least one character
    
          if(i==0) j = 0;
          else j = i+1;
    
          for( l=0; j < k; j++, l++){
             temp[l] = sentence[j];
          }
          temp[l] = '\0';
          printf("%s ",temp);
        }
        k = i;
      }
    }
    printf("\b%c",tc);
    
    int main()
    {
    
        char sent[50],last,s;
        int i,j,length,k,temp,b;
        clrscr();
        i=0;
        printf("Enter a sentence: ");
        sent[i]=getchar();
        while(sent[i]!='\n'&&sent[i]!='.'&&sent[i]!='?'&&sent[i]!='!')
        {
            sent[++i]=getchar();
        }
        last=sent[i];//storing last char
        b=i; //length of string
        printf("Reverse of sentence: ");
        for(;;)
        {
            k=b-1;// begin from last position
            temp=k;
            while(sent[k]!=' ' && k!=-1)
            k--;
            s=k;//storing space here
            b=s;
            for(j=b+1;j<=temp;j++)
            putchar(sent[j]);
            if(s!=-1)
            putchar(sent[s]);
            if(b==-1)
            break;
        }
        putchar(last);
        getch();
        return 0;
    }
    
    */
    #include<stdio.h>
    
    int main()
    {
    int ch;
    char sentence[200]; //hard set a limit of 200 character sentence
    char word[10] = {'\0','\0','\0','\0','\0','\0','\0','\0','\0'}; //hard set limit of 10 character words
    int i = 0; //character position in input
    int w = 9; //character position in word
    char terminator = '\0';
    printf("Enter a sentence:");
       while  ( (ch=getchar()) != '\n' )
           {
           if ( ch == '.' || ch == '?' || ch == '!')
              terminator = ch;
           else
             {
             sentence[i] = ch;
             i++;
             }
    //       printf("%d",i);
           }
           sentence[i] = '\0';//set last character to null
    
    
        int x;
        for ( x=i ; x >= 0 ; x-- )
            {
               if ( sentence[x] == ' ' )
               {
                printf(" ");//print the space followed by what is in the word buffer/array
    //          printf("word length %d ",w);
                printf("%c",word[0]); //probably should have a for loop here
                printf("%c",word[1]);
                printf("%c",word[2]);
                printf("%c",word[3]);
                printf("%c",word[4]);
                printf("%c",word[5]);
                printf("%c",word[6]);
                printf("%c",word[7]);
                printf("%c",word[8]);
                printf("%c",word[9]);
                w = 9 ;
                word[0] = '\0'; //fill the word buffer/array with null
                word[1] = '\0';
                word[2] = '\0';
                word[3] = '\0';
                word[4] = '\0';
                word[5] = '\0';
                word[6] = '\0';
                word[7] = '\0';
                word[8] = '\0';
                word[9] = '\0';
    //          printf("\n");
    //          printf("sentence position %d ",x);
               }
               else //assign the letters from sentence[] to letters in word[]
               {
                word[w] = sentence[x];
                w--;
    //          printf("word length %d ",w);
    //          printf("%c",sentence[x]);
               }
             }
    //print the first word because im using space to delimit the words unless i have a space at the
    //beginning of the sentence the code above will skip the first word inputed
        printf(" ");//print the space followed by what is in the word buffer/array
        printf("%c",word[0]);
        printf("%c",word[1]);
        printf("%c",word[2]);
        printf("%c",word[3]);
        printf("%c",word[4]);
        printf("%c",word[5]);
        printf("%c",word[6]);
        printf("%c",word[7]);
        printf("%c",word[8]);
        printf("%c",word[9]);
    
    
    
    if ( terminator != '\0' ) //prints a . ? or ! if it is including in the inputed sentence
        printf("%c",terminator);
    
        printf("\n");
        printf("\n");
    return 0;
    
      using System;
    
      namespace SampleString
      {
        class ReverseWordsInSetence
        {
            // Reverse words in a string (words are separated by one or more spaces).
            private static String GetReverseWordsInSetence(string sentence)
            {
                char[] stringArray = sentence.ToCharArray();
                int len = sentence.Length;
                int startIndex = 0;
    
                Swap(ref stringArray, ref startIndex , len-1);
                startIndex = 0;
    
                for (int currentIndex = 0; currentIndex < len; currentIndex++)
                { 
                    if (stringArray[currentIndex].Equals(' '))
                    {
                        Swap(ref stringArray, ref startIndex, currentIndex-1);
                    }
                    else if (currentIndex == len - 1)
                    {
                        Swap(ref stringArray, ref startIndex, currentIndex);
                    }
    
                }
    
                return new string(stringArray);
            }
    
    
            private static void Swap(ref char[] a, ref int i, int j)
            {
                int tempIndex = j;
    
                while (i < j)
                {
                    if (a[j].Equals('.'))
                    {
                        j--;
                    }
                    else
                    {
                        a[i] ^= a[j];
                        a[j] ^= a[i];
                        a[i++] ^= a[j--];
                    }
                }
    
                i = tempIndex + 2;
            }
    
            static void Main(string[] args)
            {        
               Console.WriteLine(GetReverseWordsInSetence("Hello World."));
               Console.ReadLine();
            }
        }
    }
    
     void reverse(char s[],int start,int stop){
     char t;
     while(start<stop){
        t = s[start];
        s[start]=s[stop];
        s[stop]=t;
        start++;
        stop--;
    }
    }
    
    int main() {
    
    char str[100];
    gets(str);
    
    int pos=0,begin=0,end;
    reverse(str,begin,strlen(str)-1); //since the last character is null
    
    while(pos<=strlen(str)){
        if((str[pos]==' ')||(str[pos]=='\0')||(str[pos]=='?')||(str[pos]=='!')){
            end = pos - 1; 
           reverse(str,begin,end);  
            begin = pos+1; //for the next word
        }
    
        pos++;
    
    }   
    
    cout<<str;
    return 0;
    }
    
    #include <stdlib.h>
    
    int main()
    {
    char s[20][20];
    int i=0,length=-1;
    for(i=0;;i++)
    {
        scanf("%s",s[i]);
        length++;
        if(getchar()=='\n')
            break;
    }
    for(i=length;i>=0;i--)
        printf("%s ",s[i]);
    return 0;
    }
    
    /* Outer loop goes backwards through the array, effectively reversing the sentence */
    for(i = 99; i >= 0; i--) {
    
        if(sentence[i] == ' ') {
    
            /* Inner loop goes forward, reversing the word again */
            while(sentence[i + j] != ' ') {
    
                printf("%c", sentence[i + j]);
                j++;
            }
    
            j = 1;
            printf(" ");
        }
    }
    
    /* ... */
    char sentence[100] = { ' ' }, c, tc;
    
    /* ... */
    int i = 0, j = 1, size = 0;
    
    /* Get the sentence */
    printf("Enter a sentence: \n");
    for(c = getchar(); (c != '.') && (c != '!') && 
        (c != '?') && (c != '\n'); c = getchar(), i++) {
    
        sentence[i] = c; /* Store the current character in the array */
        size++; /* Increase the sentence's size */
    }
    
    Enter a sentence:
     you can cage a swallow can't you?
    you can't swallow a cage can you?
    
    /**
     * Declare a loop counter already initialized at 1, an incremental
     * variable, as well as the size of the read sentence
     */
    int i = 1, j = 1, size = 0;
    
    /**
     * Go backward through the array, printing each sequence of characters
     * between spaces
     */
    for(i = 99; i >= 0; i--) {
    
        if(sentence[i] == ' ') {
    
            while(sentence[i + j] != ' ') {
    
                printf("%c", sentence[i + j]);
                j++;
            }
    
            j = 1; /* Reset the incremental variable */
            printf(" "); /* Print a tailing space */
        }
    }
    
    /* print the last word */
    while(sentence[i + j] != ' ') {
    
        printf("%c", sentence[i + j]);
        j++;
    }
    
    #include<stdio.h>
    
    void print_word(char[] sentence, int i) {
        int j = 1;
        while(sentence[i + j] != ' ') {
            printf("%c", sentence[i + j]);
            j++;
        }
    }
    
    int main(void) {
        char sentence[100] = { ' ' }, c, tc;
        int i = 0, j = 1, size = 0;
        printf("Enter a sentence: \n");
        for(c = getchar(); (c != '.') && (c != '!') && 
            (c != '?') && (c != '\n'); c = getchar(), i++) {
            sentence[i] = c; /* Store the current character in the array */
            size++; /* Increase the sentence's size */
        }
        tc = c; /* Get the terminating character */
        for(i = 99; i >= 0; i--) {
            if(sentence[i] == ' ') {
                print_word(sentence, i);
                printf(" "); /* Print a tailing space */
            }
        }
        print_word(sentence, i);
        printf("\b%c\n", tc);
        return 0; /* Return 0 upon successful program execution */
    }