'Swap words in string C++
I'm a new StackOverflow user! i need help. My task is to find two verbs in the string that are in the list (_words[]) and swap them. With string it's not that hard to implement, but I'm only allowed to use char.
My idea is this: I split the char(char str[]) array into words, and assign each word to a constant array(str2[]), I do the same with known verbs. Next, I check - if the word in the first array matches the known verb, then I assign the number (j) to an integer array in order to know the location of this word. Well, then, with the help of a bubble method, I change their places. But that's bad luck, I looked through the debugger, and for some reason when comparing words, even though the words are the same, the check does not pass. (sorry for my English)
Could you help me figure out what I'm doing wrong? I will be grateful!
#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] << " ";
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
