PDA

View Full Version : compare two string variables



arumita
25th May 2014, 19:14
hello^^
plz, how to compare two string variables (character by character) in qt ->to count the number of similar(or matched) characters in the same positions
thnx

ChrisW67
25th May 2014, 21:30
Start by looking at these components: an integer counter variable, a for() loop, QString::length(), QString:at(), and an if() statement.

d_stranz
26th May 2014, 00:08
Start by looking at these components: an integer counter variable, a for() loop, QString::length(), QString:at(), and an if() statement.
It would probably be helpful to clear some space on your table so you can arrange the components in different ways until you get something that looks like it might solve the problem.

arumita
26th May 2014, 12:40
thanx ChrisW67;
i tried like this:


#include <QCoreApplication>
#include <QString>
#include <QTextStream>



int main(void)
{

QTextStream out(stdout);
QString w1 = "amanda";
QString w2 = "amondy";
int n1 = w1.length();
int n2 = w2.length();
int count=0;
int i;
for(i=0;i<=n1;i++)
{
if (w1.at(i)==w2.at(i))
count++;
}

float k = (count/n1)*100;
if(k>=66)
out<<"there is a matching"<<endl;
else
out<<"no matching"<< endl;


}

it get compiled but no output did i miss something???
thnx

wysota
26th May 2014, 15:04
You surely have an off-by-one error in your loop. The last index of an N sized string is N-1.

Lesiok
26th May 2014, 15:51
count and n1 are integers. So if count < n1 result of count/n1 == 0 then k == 0.
Change to this :

float k = ((float)count/n1)*100

ChrisW67
26th May 2014, 21:35
What happens when the two strings are not the same length?