Comparing String Indexes within a loop.

What is the proper way to compare a single string index with the other string index in its proper order in C++?

For example: Comparing the strings "Plane" and "Watch"

Implementation: I am trying to compare just 'p' and 'w' then 'l' and 'a'... etc. I tried a for loop within a for loop but one string index seems to be comparing itself to all the other characters with in the string.

I thought a simple string[i] and string[j] would do the trick within there loops. Dont know what I am doing wrong.
Do you mean you want to check if string is equal to another string ?
If so
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
#include <iostream>
#include <cctype>
#include <cstring>
using namespace std ;


bool comp(char ch1[] , char ch2[] )
{
int min = strlen(ch1) >= strlen(ch2) ? strlen(ch2) : strlen(ch1) ;
for (int i = 0 ; i < min ; i++)  //There is no need for nested for loop
 {
if ( ch1[i] != ch2[i] ) 
return false ;
 }
return true ; 
}

int main ()
{
char ch1[] = "Plane" ;
char ch2[] = "Watch" ; 

if(comp(ch1,ch2)) 
cout << " Equal \n";
else 
cout << "Not Equal \n";


  return 0;
}



Note that there are many defined ways to compare strings in c++ ..
Take a look at the reference in this site and you will find everything about strings ..

Last edited on
Thank you. I've tried another way but I keep getting a error and not the outcome I am looking for. I am simply trying to compare "corresponding indexes" one at a time.


/**************************
* COSC 220
***************************
*
* File: main.cpp
*
*
*/

#include <iostream>
#include "console.h"
#include "simpio.h"
#include "strlib.h"
#include <string>
#include "lexicon.h"

using namespace std;


int main() {
setConsoleExitProgramOnClose(true);
setConsolePrintExceptions(true);
////////////////////////////////////////////////////////////

// A function that produces all the possible outcomes of only one letter being
// changed
Lexicon english("EnglishWords.dat");
string startWord;
string finishWord;
startWord = getLine("Enter a legal word (must be lowercase): ");
finishWord = getLine("Enter another legal word(must be lowercase): ");

for(int i = 0; i <= startWord.length(); i++) {
string copyWord = startWord;
for(int j = 0; j <= finishWord.length(); j++) {
for(char ch = 'a'; ch <= 'z'; ch++) {
copyWord[i] = ch; // new string from startWord that has one letter change

if (copyWord == startWord) {
continue;
}

if (english.contains(copyWord) && copyWord.at(i) == finishWord.at(j) ) {
cout << copyWord << endl;
}
}
}

}











////////////////////////////////////////////////////////////
getLine("Program finished. Press ENTER to close window(s)");
closeConsoleAndExit();
return 0;
}


Topic archived. No new replies allowed.