gpt4 book ai didi

交换字符串中两个字符的C++程序

转载 作者:行者123 更新时间:2023-11-28 00:18:10 26 4
gpt4 key购买 nike

我是 C++ 的初学者,我想编写一个简单的程序来交换字符串中的两个字符。

例如;我们输入这个字符串:“EXAMPLE”,我们给它交换这两个字符:“E”和“A”,输出应该类似于“AXEMPLA”。

我在编写以下代码时考虑的算法;很简单,希望你能通过引用代码得到它,但最后我被弄糊涂了! (我在这个网站上搜索并发现了类似的问题,但它们要么是困难和复杂的语法,要么是另一种语言)。任何建议和帮助表示赞赏。

#include <iostream>
#include <stdio.h>
#include <conio.h>
#include <cctype> // is this necessary?! I doubt between <stodio.h> and <cctype>
// By the way! when do we use double quotations instead of <> ?

using namespace std;

char array1[30], char1, char2;
int i, j, char1count = 0, char2count = 0, locofchar1[15], locofchar2[15], n1 = 0, n2 = 0;

int main()
{
cout << "Enter your string: " << endl;
gets(array1);

cout << "\nEnter the 2 characters you want to swap." << endl
<< "Character #1: ";
cin >> char1;
cout << "\nCharacter #2: ";
cin >> char2;

for (i = 0; array1[i]; i++) // A "for" loop for counting the number of repetitions of char1
// and saving the locations of char1 in a new array called "locofchar1"
if (array1[i] == char1){
char1count++;
for (j = n1; j <= char1count; j++)
locofchar1[j] = i;
n1++;
}

for (i = 0; array1[i]; i++) // Another "for" loop for counting the number of repetitions of char2
// and saving the locations of char1 in a new array called "locofchar2"
if (array1[i] == char2)
char2count++;
for (j = n2; j <= char2count; j++)
locofchar2[j] = i;
n2++;

/*

I'm already stuck at here! and I think I have some problems in the above code... We assume that the program determined the number of repetitions and their element address/location in the char1count and char2count arrays, and we want to use this informations to swap them correctly.

*/

getch();
return 0;
}

最佳答案

您忘记在多个位置放置括号。

  for (i = 0; array1[i]; i++) // Another "for" loop for counting the number of repetitions of char2
// and saving the locations of char1 in a new array called "locofchar2"
if (array1[i] == char2)
char2count++;
for (j = n2; j <= char2count; j++)
locofchar2[j] = i;
n2++;

如果没有大括号,在C/C++中,只有if之后的第一个过程才符合条件。其余无条件执行。所以每次都会执行上面代码中的for循环。所以加上大括号:

       if (array1[i] == char2) {
char2count++;
for (j = n2; j <= char2count; j++) {
locofchar2[j] = i;
n2++;
}
}

为每个条件和每个循环添加大括号是一种很好的做法,这样您就不会忘记哪些行属于这些条件/循环。

关于交换字符串中两个字符的C++程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28958308/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com