PDA

View Full Version : index of a string that appears n times



deepikha
19th October 2017, 10:30
hello i am able to get index of "@" in c++ but not in qt. i dont know what i have to use to find("@",found+1,q)


#include <iostream> // std::cout
#include <string> // std::string

int main ()
{
std::string str ("msel@-txt/l<seq_name>@#ifndef I_MSEL_@-txt/u<seq_name>@_H");
std::string tag ("@");



// different member versions of find in the same order as above:
std::size_t found = str.find(tag);
if (found!=std::string::npos)
std::cout << "first '@' found at: " << found << '\n';

for (int i = 0; i <= 5; i++)
{ int q =1;
found=str.find("@",found+1,q);
q++;
if (found!=std::string::npos)
std::cout << " '@' found at: " << found << '\n';
}

return 0;
}

jimbo
19th October 2017, 11:21
Hello,

From Qt Creator help - QString
http://doc.qt.io/qt-5/qstring.html#indexOf-6

#include <QString>

QString x = "sticky question";
QString y = "sti";
x.indexOf(y); // returns 0
x.indexOf(y, 1); // returns 10
x.indexOf(y, 10); // returns 10
x.indexOf(y, 11); // returns -1, if not found

Regards

deepikha
19th October 2017, 11:57
hi i have one more doubt string that indicates with character '@' and next to it string in the "" data should be extracted and stored in variable so for example
string str ("msel@"txt/l<seq_name>"#ifndef I_MSEL_@"txt/u<seq_name>"_H");

i need output to be -txt/l<seq_name>
then -txt/u<seq_name>

can you help me out with this

jimbo
20th October 2017, 00:05
You now have the index of @.

From the link I gave:-
look for
QString->length
QString->right
QString->left

Just remember the index starts at zero.

Santosh Reddy
20th October 2017, 05:30
Looks like you want to split the string, see if this helps


#include <QString>
#include <QDebug>

int main ()
{
QString str ("msel@-txt/l<seq_name>@#ifndef I_MSEL_@-txt/u<seq_name>@_H");
QString tag ("@");

QStringList list = str.split(tag);

foreach(const QString & s, list)
qDebug() << s;

return 0;
}

geekowl
20th October 2017, 09:04
Well for c++ - native : you can use iterators..




void findInNormal()
{
std::string str ("msel@-txt/l<seq_name>@#ifndef I_MSEL_@-txt/u<seq_name>@_H");
auto found = std::find(str.begin(),str.end(),'@');

while(found != str.end())
{
qDebug() << "'@' found at: " << std::distance(str.begin(),found++) << '\n';
found = std::find(found,str.end(),'@');
}
}


in qt - string style might be like this...




void findInQt()
{
std::string str ("msel@-txt/l<seq_name>@#ifndef I_MSEL_@-txt/u<seq_name>@_H");
QString qstr = QString::fromStdString(str);
auto index = qstr.indexOf('@');
while(index != -1)
{
qDebug() << "'@' found at: " << index << '\n';
index = qstr.indexOf('@',++index);
}
}