如何交换在函数中作为指针传递的 2 个字符串
How to swap 2 strings passed as pointers in a function?
我必须将作为指针传递给函数的 2 个字符字符串交换:布尔swap_strings(字符* 字符串 1、字符* 字符串 2)如果两个字符串的长度不同,则返回 false,否则如果交换有效,则返回 true;
我怎样才能意识到这一点?为什么这是不正确的:
#include <iostream>
using namespace std;
bool swap_strings(char * string1, char * string2) {
char * s;
char * s2;
char * tmp = nullptr;
for (s = string1; *s != ' '; ++s);
for (s2 = string2; *s2 != ' '; ++s2);
if ((s - s2) != 0) {
return false;
}
else {
tmp = *&string1;
string1 = *&string2;
string2 = *&tmp;
cout << tmp << string1 << string2<< endl;
}
return true;
}
int main()
{
bool da = false;
char s1[] = "hallo1";
char s2[] = "ababab";
da = swap_strings(s1, s2);
cout << da << s1 << s2 <<endl;
}
除非你想复制已经编写的代码,否则你需要使用 strlen
来获取字符串的长度:
unsigned int s1len = strlen(string1);
unsigned int s2len = strlen(string2);
if (s1len != s2len)
return false;
如果您无法使用标准库函数(愚蠢的要求):
unsigned int s1len = 0;
for (char* s = string1; *s != ' '; s++, s1len++);
将做同样的事情(你必须对两个字符串都这样做)。
之后,交换很简单:
for (unsigned int i = 0; i < s1len; ++i)
{
std::swap(string1[i], string2[i]);
}
或
for (unsigned int i = 0; i < s1len; ++i)
{
// these 3 lines are identical to what is done in std::swap
char t = string1[i];
string1[i] = string2[i];
string2[i] = t;
}
您也可以(毫无疑问,破坏分配的目的),只需更改指针值:
bool swap_strings(char*& string1, char*& string2)
{
char* t = string1;
string1 = string2; // string1 will now point to string2
string2 = t; // string2 will now point to what use to be string1
return true;
}
我说它违背了作业的目的,因为你没有做任何复制,当你这样做时,长度要求是无关紧要的。 当您传入数组时(例如,如果您将输入声明为 char a[] = "abcd";
- 您在main
中已经这样做),它也不会工作(例如不会编译)。
您可以简单地循环遍历传递的字符串,然后进行逐个字符交换。
例如
#include <assert.h>
#include <iostream>
bool swap_strings(char * const s1, char * const s2) {
assert(s1 != nullptr);
assert(s2 != nullptr);
if (strlen(s1) != strlen(s2))
return false;
char * pch1 = s1;
char * pch2 = s2;
char temp;
while (*pch1 != ' ') {
temp = *pch1;
*pch1 = *pch2;
*pch2 = temp;
++pch1;
++pch2;
}
return true;
}
int main() {
using namespace std;
char s1[] = "hallo1";
char s2[] = "world2";
if (swap_strings(s1, s2)) {
cout << s1 << endl;
cout << s2 << endl;
}
}
相关文章:
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 初始化或分配空字符串文字到指向 C 中的 char 的指针或指向 C++ 中 const char 的指针的原因是什么
- 使用指针初始化 char 数组或字符串 C++
- 指针保留字符串
- Visual c ++,使用字符串引用/指针调用 dll 函数
- strcpy 在类中无法使用字符串指针
- C++为 void 指针分配一个字符串
- OpenGL 统一名称指针作为字符串
- 如何将字符串指针数组转换为字符串类型的智能指针向量?
- 转换指针引用的字符串
- 未分配释放C++(C 字符串)指针
- 为什么 C 样式字符串的工作空指针检查不?
- 为什么多维数组中的空字符串文本衰减为空指针?
- 使用终止程序的指针在数组中输入字符串
- 将指针作为缓冲区传递到第一个字符串元素
- 指针 - 字符串C
- C++:更改指针字符串的值
- 使用带字符指针字符串的基于范围的For循环
- 转换/解析指针字符串和双精度
- 有问题分配字符串指针字符串值