即日起在codingBlog上分享您的技术经验即可获得积分,积分可兑换现金哦。

【补充】题目: 编写一个C函数,将”I am from shanghai ”倒置为”shanghai from am I”,及将句子中的单词位置倒置,而不改变单词内部结构.

编程语言 qq_38076413 14℃ 0评论

方法一:

#include 
#include 
#include 

void my_strcpy(char *result,char *str,int len)               //复制长度为len的字符串
{
 while(len)
 {
  *result = *str;
  str++;
  result++;
  len--;
 }
}

void change(char *str,char **a)
{
 int i = 0;                   //记录行数
 int j = 0;
 int count = 0;               //记录每行元素的个素
 char *temp = NULL;
 temp = (char*)malloc(sizeof(char));

 while(*str)
 {
  if(*str == ' '||*str == '\0')
  {
   my_strcpy(a[i],str-count,count);
   i++;
   count = 0;
  }
  count++;
  str++;
 }
 if(*str == '\0')
 {
  my_strcpy(a[i],str-count,count);
  count = 0;
  i++;
 }
 
 for(j = 0;j < i/2;j++)
 {
  strcpy(temp,a[j]);
  strcpy(a[j],a[i-j-1]);
  strcpy(a[i-j-1],temp);
 }
 for(j = 0;j < i;j++)
 {
  printf("%s ",a[j]);
 }
 printf("\n");

 free(temp);
}

int main()
{ 
 int i = 0;
 char str[] = "I am from shanghai";
 char *a[4] = {0};

 for(i = 0;i < 4;i++)
 {
  a[i] = (char*)malloc(sizeof(char)*20);
 }

 change(str,a);
 
 for(i = 0;i < 4;i++)
 {
  free(a[i]);
 }
 return 0;

}



方法二:

#include 
#include 

void change(char *str)
{
 char temp;
 char *p = str;
 char *start = str;
 char *end = str;

 while(*p != '\0')
 {
  p++;
  end++;
 }
 end = p-1;
 p = str;
 while(*p!='\0')
 {
  while(start < end)
  {
   temp = *start;
   *start = *end;
   *end = temp;
   start++;
   end--;
  }
  p++;
 }
}

void change1(char *str)
{
  char *p = str;
  char *start = p;
  char *end = p;
  char temp;

  while(*p != '\0')
  {
   if(*p ==' '||*p == '\0')
   {
    end = p-1;
    while(start < end)
    {
     temp = *start;
     *start = *end;
     *end = temp;
     start++;
     end--;
    }
    start = end = p+1;
   }
   p++;
  }
  end = p-1;
  while(start < end)
  {
   temp = *start;
   *start = *end;
   *end = temp;
   start++;
   end--;
  }
}

int main()
{
  char str[100];

  printf("please input string:\n");
  gets(str);

  change(str);
  change1(str);

  printf("the result is :%s\n",str);
}





转载请注明:CodingBlog » 【补充】题目: 编写一个C函数,将”I am from shanghai ”倒置为”shanghai from am I”,及将句子中的单词位置倒置,而不改变单词内部结构.

喜欢 (0)or分享 (0)
发表我的评论
取消评论

*

表情