C字符串程序

mrb*_*ppy 15 c string

我在学校接受了一项任务,即编写一个程序

  • 读三个字符串
  • 在动态分配的内存中存储第三个字符串
  • 按字母顺序打印出第一个单词的最后4个字母.

这是我到目前为止的程序.字符串都存储在不同的变量中,这使得它们难以排序.如果有人能帮助我完成这个项目,我将非常感激.

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

int main()
{
   char word1[101];
   char word2[101];
   char* word3;
   char buffer[101];
   scanf("%s", word1);
   scanf("%s", word2);
   scanf("%s", buffer);
   word3 = (char *) malloc(strlen(buffer)+1);
   strcpy(word3, buffer);

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

bri*_*ner 2

使用strcmp按字母顺序查找第一个单词。

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

int main()
{
   char word1[101];
   char word2[101];
   char* word3;
   char buffer[101];
   scanf("%s", word1);
   scanf("%s", word2);
   scanf("%s", buffer);

   char* smallestword = word1;
   if (strcmp(smallestword,word2) > 0) // smallest is bigger than word2
     smallestword = word2;
   if (strcmp(smallestword,buffer) > 0) // smallest is bigger than buffer
     smallestword = buffer;

   word3 = (char *) malloc(strlen(smallestword)+1);
   strcpy(word3, buffer);
   return 0;
}
Run Code Online (Sandbox Code Playgroud)