【问题标题】:Reversing a string using two pointers in C在C中使用两个指针反转字符串
【发布时间】:2019-04-15 02:06:18
【问题描述】:

我正在尝试使用指针 sptr1 和 sptr2 反转字符串,len 给出了输入字符串的正确长度,但字符串没有反转,str1 也没有显示在我的终端上。请提供一些见解

#include<stdio.h>
void main()
{
 char str1[10];
 char temp;

 char *sptr1;
 char *sptr2;
 int len;
 printf("Enter a string:");
 scanf("%s",&str1);
 sptr1=str1;
 sptr2=str1;
 while(*sptr1!='\0')
 {
  sptr1++;
 }
 len=sptr1-str1;
 printf("Length of the string:%d",len);

 while(len!=0)
 {
  temp=*sptr1;
  *sptr1=*sptr2;
  *sptr2=temp;

  sptr1--;
  sptr2++;
  len=len-1;
 }
  printf("%s",str1);
 }

【问题讨论】:

  • 它会产生什么,你真正想拥有什么?
  • 先生,我需要将存储在 str1 中的输入字符串在一段时间后反转。即使 str1 的 printf 存在,输出屏幕也只是接受字符串并显示长度
  • 看起来你正在反转字符串两次。

标签: c


【解决方案1】:

while(*sptr1!='\0')... sptr 指向字符串的空终止符之后,您将使用第一个字符切换此空终止符。例如。您将空终止符移动到索引0。在开始反向之前,您必须减少 sptr

您还应该将len 减少2,否则您将遍历整个数组并将已经切换的字符切换回来。

其他一些小错误:
main 应该返回 int,而不是 void
scanf("%s", &amp;str1); 应该是 scanf("%s", str1);str1 已经衰减为指针。
您应该在您的 printf 语句中添加 \n 以使输出位于不同的行中,而不是 1 长行。

#include<stdio.h>

int main() {
    char str1[10];
    char temp;
    
    char *sptr1;
    char *sptr2;
    
    int len;
    printf("Enter a string:\n");
    scanf("%s", str1);
    sptr1 = str1;
    sptr2 = str1;
    
    while ( *sptr1 != '\0') {
        sptr1++;
    }
    
    len = sptr1 - str1;
    printf("Length of the string:%d\n", len);
    sptr1--;
    
    while (len > 0) {
        temp = *sptr1;
        *sptr1 = *sptr2;
        *sptr2 = temp;

        sptr1--;
        sptr2++;
        len = len-2;
    }
    printf("%s\n", str1);
}

现场观看:https://ideone.com/WAnQLi

【讨论】:

  • 是的,先生,谢谢!我将检查各种其他示例和类型
  • 先生,您能解释一下为什么是 len=len-2 吗?
  • 为 "aiaz" 运行此代码,它没有显示完全相反。我认为 while 应该改为 (len>0)
  • 你说得对,改成len&gt;0。您只需要迭代一半以上的数组。考虑输入abcd:您切换adbc(到此即可完成),但是当您遍历整个数组时,您也切换b 和@987654344 @、ad 再次得到原始字符串。
【解决方案2】:
#include<stdio.h>
#include<string.h>
int main(int argc, const char * argv[])
    {
        char s[]="hello";
        strrev(s);
        puts(s);
        return 0;
    }

尝试 strrev 函数:

char *strrev(char *str);

【讨论】:

    【解决方案3】:

    @mch 的代码只有一个错误

    len = len - 2;
    

    正因为如此,程序将无法正确处理长度为偶数的字符串。 我写代码是因为可读性更高。

    #include <stdio.h>
    
    
    int main()
    {
        char str[10];
        printf("Enter a string:\n");
        scanf("%s", str);
        char *ptr1, *ptr2;
        ptr1 = ptr2 = str;
        size_t len = 0;
    
        while (*ptr1) {
           ++ptr1, ++len;
        }
        printf("Length of the string:%u\n", len);
    
        for (int k = 0; k < len / 2; ++k) {
            char temp = *(--ptr1);
            *ptr1 = *ptr2;
            *ptr2++ = temp;
    
        }
    
        printf("%s\n", str);
    
    
    }
    

    【讨论】:

      【解决方案4】:

      只是一个额外的答案,非常小心缓冲区溢出问题。还有一个小细节,你真的不需要len 变量。

      下面的注释代码显示了一种小心处理内存写入的方法。

      #include <stdio.h>
      
      // Here a way to use constants both as integer and strings
      // See https://stackoverflow.com/questions/5459868
      #define STR_HELPER(x) #x
      #define STR(x) STR_HELPER(x)
      
      // Let's define a max length
      #define MAX_STRING_LENGTH 10
      
      void main()
      {
        char sptr[MAX_STRING_LENGTH + 1]; 
      
        char *sptr1=sptr,*sptr2=sptr;
        char swap;
      
        printf("Enter a string (" STR(MAX_STRING_LENGTH) " at most): ");
      
        // Here, limit the input to sptr size - 1
        // (let the last index for the null character)
        // Example : "%10s" means "at most 10 characters, additional ones
        //           will be removed."
        scanf("%" STR(MAX_STRING_LENGTH) "s",&sptr);
      
        // Finding the last character BEFORE the NULL character
        while(*(sptr2+1) != '\0') sptr2++;
      
        // Swaping
        while (sptr2 > sptr1)
          {
            printf("\t-> swaping %c <-> %c\n", *sptr1, *sptr2);
            swap=*sptr1;
            *sptr1=*sptr2;
            *sptr2=swap;
            sptr1++,sptr2--;
          }
      
        printf("Result : [%s]\n",sptr);
      }
      

      示例(奇偶长度的字符串):

      user:~$ ./a.out 
      Enter a string (10 at most): abc
              -> swaping a <-> c
      Result : [cba]
      user:~$ ./a.out 
      Enter a string (10 at most): abcd
              -> swaping a <-> d
              -> swaping b <-> c
      Result : [dcba]
      user:~$ ./a.out
      Enter a string (10 at most): abcdefghijklmnopqrstuvwxyz
              -> swaping a <-> j
              -> swaping b <-> i
              -> swaping c <-> h
              -> swaping d <-> g
              -> swaping e <-> f
      Result : [jihgfedcba]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-11-21
        • 2012-05-05
        • 2020-02-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多