【发布时间】:2022-01-24 11:30:45
【问题描述】:
我是 StackOverflow 的新用户!我需要帮助。我的任务是在列表中的字符串中找到两个动词 (_words[]) 并交换它们。使用字符串实现起来并不难,但我只能使用char。
我的想法是这样的:我将char(char str[]) 数组拆分为单词,并将每个单词分配给一个常量数组(str2[]),我对已知动词也是如此。接下来,我检查 - 如果第一个数组中的单词与已知动词匹配,那么我将数字 (j) 分配给一个整数数组,以便知道该单词的位置。好吧,那么,在冒泡方法的帮助下,我改变了他们的位置。但是运气不好,我查看了调试器,并且由于某种原因在比较单词时,即使单词相同,检查也没有通过。 (对不起我的英语)
你能帮我弄清楚我做错了什么吗?我将不胜感激!
#pragma warning(disable:4996)
#include <iostream>
#include <conio.h>
void words() {
char str[] = "i like to make programm";
char _words[] = "like make";
char* l1 = strtok(_words, " ");
const char* z[10];
const char* str2[10];
const char* temp[1];
int arr_num[2];
int i = 0, control = 0;
int word = 0;
char* stream;
while (l1 != NULL)
{
z[i] = l1;
l1 = strtok(NULL, " ");
i++;
}
for (int i = 0; i < 2; i++) {
cout << z[i] << endl;
}
i = 0;
for (int i = 0; i < strlen(str); i++) {
if (str[i] == ' ') {
word++;
}
}
word++;
stream = strtok(str, " ");
while (stream != NULL)
{
str2[i] = stream;
if(stream == z[0]) cout << "lol";
stream = strtok(NULL, " ");
i++;
}
for (int i = 0; i < word; i++) {
cout << str2[i] << endl;
}
for (int i = 0; i < 2; i++) {
for (int j = 0; j < word; j++) {
if ((z[i] == str2[j]) && (control < 3)) {
control++;
arr_num[i] = j;
}
}
}
if (control == 2) {
temp[0] = str2[arr_num[0]];
str2[arr_num[0]] = str2[arr_num[1]];
str2[arr_num[1]] = temp[0];
}
for (int i = 0; i < word; i++) {
cout << str2[i] << " ";
}
}
【问题讨论】:
-
我们不是读心术的人。我们阅读代码。您的代码应为 included in your question 格式正确的 minimal reproducible example,并包括任何示例输入、预期输出、实际输出以及迄今为止的调试工作和发现。
-
当你比较单词时,你真的比较
char*s吗?如果这些指针指向不同的位置,它们就会变得不同,但是指向位置的内容可能是相同的。 -
对不起,我忘了贴代码
-
我想你的任务是交换给定字符串(字符数组)中的单词,例如“red apple is the 最甜蜜的一个。”变成“sweetest apple is the red one。”这不仅涉及将两个选择的单词相互替换,而且还可能在它们之间移动内容......
-
@zerocukor287 ,是的,我按照你说的做。你能推荐一个替代方案吗?