21xrx.com
2024-03-29 08:48:18 Friday
登录
文章检索 我的文章 写文章
反转字符串的C程序
2021-07-07 08:44:07 深夜i     --     --
C

用于反转用户输入的字符串的 C 程序。 如果字符串为“hello”,则输出为“olleh”。 C 程序使用 strrev 反转字符串,而不使用 strrev、递归和指针。 反转时保持不变的字符串是回文。

 

使用 strrev 反转 C 中的字符串

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


int main()
{
   char s[100];

   printf("Enter a string to reverse\n");
   gets(s);

   strrev(s);

   printf("Reverse of the string: %s\n", s);

   return 0;
}

C反向字符串程序输出:

编译程序时,您可能会收到以下消息:“警告:函数 'strrev' 的隐式声明在 C99 [-Wimplicit-function-declaration] 中无效”。 在这种情况下,我们必须反转没有 strrev 的字符串(参见下一个程序)。

下载反向字符串程序。

C程序反转字符串中的单词

没有 strrev 函数的字符串反转

我们在不使用 strlen 函数的情况下找到字符串的长度,然后使用 for 循环以相反的顺序(从末尾到开头)将其字符复制到新字符串中。

 

#include <stdio.h>


int main()
{
   char s[1000], r[1000];
   int begin, end, count = 0;

   printf("Input a string\n");
   gets(s);

   // Calculating string length

   while (s[count] != '\0')
      count++;

   end = count - 1;

   for (begin = 0; begin < count; begin++) {
      r[begin] = s[end];
      end--;
   }

   r[begin] = '\0';

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

   return 0;
}

使用递归反转字符串的C程序
 

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


void reverse(char*, int, int);

int main()
{
   char a[100];

   gets(a);

   reverse(a, 0, strlen(a)-1);

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

   return 0;
}

void reverse(char *x, int begin, int end)
{
   char c;

   if (begin >= end)
      return;

   c          = *(x+begin);
   *(x+begin) = *(x+end);
   *(x+end)   = c;

   reverse(x, ++begin, --end);
}

在递归方法中,我们交换字符串开头和结尾的字符并向字符串的中间移动。 由于重复的函数调用,此方法效率低下。

使用堆栈反转字符串

我们可以使用堆栈来反转字符串。 将字符串中的字符一个一个推到最后。 通过存储弹出的元素创建另一个。

使用指针反转字符串的C程序

现在我们将使用指针或不使用库函数 strrev 来反转字符串。

#include<stdio.h>
 
int string_length(char*);
void reverse(char*);
 
main()
{
   char s[100];
 
   printf("Enter a string\n");
   gets(s);
 
   reverse(s);
 
   printf("Reverse of the string is \"%s\".\n", s);
 
   return 0;
}
 
void reverse(char *s)
{
   int length, c;
   char *begin, *end, temp;
 
   length = string_length(s);
   begin  = s;
   end    = s;
 
   for (c = 0; c < length - 1; c++)
      end++;
 
   for (c = 0; c < length/2; c++)
   {        
      temp   = *end;
      *end   = *begin;
      *begin = temp;
 
      begin++;
      end--;
   }
}
 
int string_length(char *pointer)
{
   int c = 0;
 
   while( *(pointer + c) != '\0' )
      c++;
 
   return c;
}

 

  
  
下一篇: C 中的回文

评论区

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