C - 仅用一个指针递归地交换2个字符

标签 c

我需要写一个函数: void swap(char*s1,char*s2);

该函数将替换字符串 1 和 2 的内容。 限制条件: 在函数中,任何地方都没有使用[],而是通过使用指针来进行性能,此外,必须与投票者进行旅行,这意味着他们实际上会根据需要移动到另一个单元格,并且不会一直停留在同一个位置。 • 函数中无循环,即递归工作。

我使用指向指针 str** 的指针执行了该函数,但必须将其更改为只有一个指针 str 并递归。我该如何更改它?

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

int main()
{
char *str1="abc",*str2="xyz",*pRev;
 swap(&str1, &str2); 
 printf("str1 is %s, str2 is %s", str1, str2); 
 getchar(); 
  return 0;
}
//need *str NOT **str
  void swap(char **str1, char **str2);
    char * RevWords (char * str, int size);
    void swap(char **str1, char **str2) 
    { 
      char *temp = *str1_ptr; 
      *str1_ptr = *str2_ptr; 
      *str2_ptr = temp; 
    }   

交换后方法:

str2=“abc”,str1=“xyz”

最佳答案

这显然不是一个理想的解决方案,但为您提供了一些可以使用的东西。 然而,只有当你有相同长度的字符串时,这才有效(如上所述)(或者是的,你必须分配内存+你需要知道字符串的长度)。但除此之外,我认为这可以回答您的问题。

这适用于递归,并且取决于两个字符串长度相同并且每个字符串末尾都包含零字符的事实。

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

void swap(char* str1, char* str2)
{
    // if both of them are zero characters then stop
    if (*str1 == '\0' && *str2 == '\0')
        return;
    // else swap the contents of the pointers
    else
    {
        char tmp = *str1;
        *str1 = *str2;
        *str2 = tmp;
        // advance both pointer and swap them too if thye are not '\0'
        swap(++str1, ++str2);        
    }
}

int main()
{
    char str1[] = "abc\0\0\0"; // padded with zeros to be the same length as str2
    char str2[] = "xyz123"; // the last '\0' is automatically added

    swap(str1, str2);
    printf("str1 is %s, str2 is %s", str1, str2);
    getchar();

    return 0;
}

关于C - 仅用一个指针递归地交换2个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55801761/

相关文章:

c - 结构体指针中的 "dereferencing pointer to incomplete type”

C 编程逻辑错误?

返回姓名首字母的 C 程序 (CS50)

c - 通过时间延迟增加整数

在windows下编译带有unix风格头文件的C程序

c - 为什么 fread 返回零以及文件何时包含内容

c - C中的整数SIMD指令AVX

c - 尝试收集我的 Linux 环境的环境变量,但我不断遇到段错误

c - 多维数组中的字符串没有终止 NUL 字符?

创建多个文件并且每个文件都打印完全相同的东西--C