How to swap 2 strings passed as pointers in a function?
我必须交换2个作为指针传递给函数的字符字符串:bool交换字符串(char*string1,char*string2)如果两个字符串的长度不相同,则返回false;否则,如果交换成功,则返回true;
我怎么能意识到这一点?为什么不正确:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | #include <iostream> using namespace std; bool swap_strings(char * string1, char * string2) { char * s; char * s2; char * tmp = nullptr; for (s = string1; *s != '\0'; ++s); for (s2 = string2; *s2 != '\0'; ++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; } |
除非您想复制已经编写的代码,否则需要使用
1 2 3 4 | unsigned int s1len = strlen(string1); unsigned int s2len = strlen(string2); if (s1len != s2len) return false; |
如果不能使用标准库函数(愚蠢的要求):
1 2 | unsigned int s1len = 0; for (char* s = string1; *s != '\0'; s++, s1len++); |
将执行相同的操作(必须对两个字符串执行此操作)。
之后,交换很简单:
1 2 3 4 | for (unsigned int i = 0; i < s1len; ++i) { std::swap(string1[i], string2[i]); } |
或
1 2 3 4 5 6 7 | 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; } |
您也可以(毫无疑问,违背了分配的目的)简单地更改指针值:
1 2 3 4 5 6 7 | 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; } |
我说它破坏了任务的目的,因为你没有做任何复制,长度要求是无关的,当你这样做。当您传入数组时(例如,如果您将输入声明为
您可以简单地循环传递的字符串,并进行逐字符交换。
例如
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | #include #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 != '\0') { 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; } } |