QList<QString> to QString.arg() - qt

I have the following QString:
QString funcProxy = "executeProxy(\"%1\", \"%2\", \"%3\")";
The data for each on is in:
QList<QString> listProxy;
How would I go about adding the data in listProxy to funcProxy using the arg() method?
funcProxy.arg(??);
Thanks

Regarding the answer from #owacoder, you do not actually need the replace function, the following should work correclty:
for (int i = 0; i < listProxy.size(); ++i) {
funcProxy = funcProxy.arg(listProxy.at(i));
}
Why you ask: From the documentation on QString::arg()
Returns a copy of this string with the lowest numbered place marker replaced by string
Thus it replaces the lowest number with the string in the arg call. First iteration contains %1, %2 and %3, so it replaces %1. Next iteration contains %2 and %3, thus replaces %2.
Alternatively if you have control over funcProxy you can do the following given you can change your list to a QStringList:
QString funcProxy = "executeProxy(\"%1\")";
QStringList listProxy{"a", "b", "c"};
funcProxy = funcProxy.arg(listProxy.join("\", \""));

If you know you'll have exactly 3 elements in your list, you can do this:
funcProxy.arg(listProxy.at(0)).arg(listProxy.at(1)).arg(listProxy.at(2));
Otherwise, you could use this:
for (int i = 0; i < listProxy.size(); ++i)
funcProxy.replace(QString("%%1").arg(i+1), listProxy.at(i));

Related

char array variable name want to use in variable in Arduino IDE

i created char array
char Jan1[] = "1,2,3,4";
char Jan2[] = "5,7,3,4";
char Jan3[] = "10,9,3,4";`
the above char arrays i want to use it as shown below in for loop each time it will iterate and print, print is an example i am processing this string further in code, but it is giving error. if instead of yy i use Jan1 then it is printing properly. what is the other way i can use yy as to get print char array as string.
for(int i=1;i<=2;i++)
{
char yy[4];
sprintf(yy,"Jan%d",i);
String presentMonth = String(yy);
Serial.print(presntMonth);
}
So by the comments it seems that what you want is to print the contents of the JanX variable based on an index variable.
Missunderstanding
First of all you need to understand the difference between strings as datatypes and variable names. The former are ways to represent a sequence of characters (used mainly, but not only, to display output messages to any sort of output like a file, a console etc..). The latter are names that you use while coding and they can be whatever you want but they will never appear in the final program.
This for instance creates a String (datatype) named hello which contains the sequence of characters h e l l o.
String hello = "Hello";
Nothing prevents me to assign goodbye to it:
hello = "Goodbye"
Serial.print(hello); // This will print "Goodbye"
In general (apart from very hacky ways) you can't retrieve the name of the variable from your program and have them ready in your executable.
Issue
char Jan1[] = {'1','2','3'};
String yy = "Jan1"
Serial.print(yy); // This will print "Jan1"
To print the items in Jan1 you need to iterate through the values.
void printItems(char* s,int N){
for ( i = 0; i<N; i++ )
{ Serial.print(s[i]); }
}
Since Arduino provides the String class, however, it would be better to do this:
String Jan1 = "1,2,3,4";
Serial.print(Jan1); // This iterates under the hood, takes care of the length, and all the good stuff.
Solution
You want to do something a little more advanced, you want to point to a particular string based on a variable, then print the content of the retrieved string.
I can think of two ways for doing so: by using an list of strings or via a hashmap.
List of strings
String list[] = {"1,2,3,4" , "4,5,6,7", ... };
for(int i = 0; i < sizeof(list)/sizeof(String) ; i++ ){
Serial.print(list[i])
}
Hashmap
The reason I am thinking about this is because you want a string as the "index" that let's you lookup the string, so you can "search" by name. The easiest and quickest method I can think of is to declare an array of structs string_name;string_content and use strcmp to iterate through the array of structs until the needed one is found.
typedef struct{ String name; String content;} element_t;
element_t dict[] = { {"Jan1","1,2,3,4"} , {"Jan2","2,3,4,5"} ... }'
// Note this is not even close to perfect (for instance lacks check if key does not exists)
String lookup(element_t DICT, int DICT_SIZE, String key){
// Iterate through the elements, use strcmp to retrieve it
for(int i = 0; i < DICT_SIZE ; i++ ){
if(strcmp(DICT[i].name,key) {
return DICT[i].content;
}
}
}
// Now create the key, as in your code, and then lookup.
for(int i=1;i<=2;i++)
{
char yy[4];
sprintf(yy,"Jan%d",i);
String presentMonth = lookup(dict,dict_size,yy);
Serial.print(presntMonth);
}

Dispaly three items of QStringList in one QtableWidget element

I have a binary vector (it is in hex)
For Example -
x={0x06, 0xfc, 0x47}
I want to save it in a QStringList and then read it from the list and display all of them in one element of QTableWidget. How can I do this? I did this previously with a for loop but it only displays the last vector element (0x47) in the table.
Thanks.
You can do it like this:
QStringList list;
for(int i = 0; i < vector.size(); ++i)
{
list.append(QString::number(vector[i], 16));
}
// i - row, j - column in function join put your separator(for example "\n" if you want all items in new row)
ui->tableWidget->setItem(i,j, new QTableWidgetItem(list.join("\n"));

QStringList "index out of range"

I am trying to reverse the words within a QStringList. Below is the code up to now, but I keep on getting a "Index out of Range" error. From the error it would seem that I am trying to use data that is out of scope, but not able to figure out my problem.
QString reversed;
QStringList reversedlist;
QStringlist list = input.split(" ");
for (int i=0;i<list.length(); ++1)
reversedlist[i] = list[list.length() -1 -i];
reversed = reversedlist.join(" ");`
Thanks
As pointed out by #ThorngardSO, the reversedlist is initially empty, and you are trying to access the invalid index in your loop code. You should add values to the list using one of the following functions:
STL-compatible function push_back() (inserts value at the end of the list)
STL-compatible function push_front() (inserts value at the beginning of the list)
Qt function append() (Qt alternative for push_back)
Qt function prepend() (Qt alternative for push_front)
As you see, prepend() inserts the element at the beginning of the list, that is why it makes the reversing of the list very simple:
for (int i = 0; i < list.length(); ++i) {
reversedlist.prepend(list[i]);
}
Also, note that there is a typo in your loop: it should be ++i instead of ++1.
Your reversedList is initially empty. You have to actually append the items, like this:
reversedlist.push_back (list[list.length () - 1 - i]);
Naturally, trying to access non-existing items via reversedList[i] does not work and throws the index-out-out-range error.
You got the index out of range as there is no sting inside the QStringList reversedlist. So when your code reach the line reversedlist[0], it throw the "index out of range" error. And you can read the value using [0] and cant assign.
if you want to assign the value to a particular index of the QStringList.
QString reversed;
QStringList reversedlist;
QString input="123 456 789 000";
QStringList list = input.split(" ");
for (int i=0;i<list.length(); ++i){
//value to particular index
reversedlist.insert(i,list[list.length() -1 -i]);
}
reversed = reversedlist.join(" ");
qDebug() << reversed;

Getting a part of a QMap as a QVector

I have some elements in a QMap<double, double> a-element. Now I want to get a vector of some values of a. The easiest approach would be (for me):
int length = x1-x0;
QVector<double> retVec;
for(int i = x0; i < length; i++)
{
retVec.push_back(a.values(i));
}
with x1 and x0 as the stop- and start-positions of the elements to be copied. But is there a faster way instead of using this for-loop?
Edit: With "faster" I mean both faster to type and (not possible, as pointed out) a faster execution. As it has been pointed out, values(i) is not working as expected, thus I will leave it here as pseudo-code until I found a better_working replacement.
Maybe this works:
QVector<double>::fromList(a.values().mid(x0, length));
The idea is to get all the values as a list of doubles, extract the sublist you are interested in, thus create a vector from that list by means of an already existent static method of QVector .
EDIT
As suggested in the comments and in the updated question, it follows a slower to type but faster solution:
QVector<double> v{length};
auto it = a.cbegin()+x0;
for(auto last = it+length; it != last; it++) {
v.push_back(it.value());
}
I assume that x0 and length take care of the actual length of the key list, so a.cbegin()+x0 is valid and it doesn't worth to add the guard it != a.cend() as well.
Try this, shouldn work, haven't tested it:
int length = x1-x0;
QVector<double> retVec;
retVec.reserve(length); // reserve to avoid reallocations
QMap<double, double>::const_iterator i = map.constBegin();
i += x0; // increment to range start
while (length--) retVec << i++.value(); // add value to vector and advance iterator
This assumes the map has actually enough elements, thus the iterator is not tested before use.

QRegExp match certain letters?

I'm working with DNA, RNA and protein sequences and QRegExp doesn't work for me to detect if
the sequence contains only certain characters.
For example unambiguous contains only acgt :
seq.contains(QRegExp("[gatc]"))
Doesn't work for me. How can I correct that ?
You're looking for whether the sequence contains characters other than gatc. You also shouldn't be using the deprecated QRegExp in Qt 5. So:
#if (QT_VERSION >= QT_VERSION_CHECK(5,0,0))
QRegularExpression invalid("[^gatcGATC]");
#else
QRegExp invalid("[^gatcGATC]");
#endif
if (seq.contains(invalid)) {
qDebug() << "invalid sequence!";
...
}
by default QRegExp is case sensitive.
QRegExp ( const QString & pattern, Qt::CaseSensitivity cs = Qt::CaseSensitive
You should add the parameter to make it case insensitive.
Misunderstanding the OP request. This solution is for finding subsequences only containing all 4 elements once.
Since regular expressions cannot count occurrences, you will need to check for any possible match. Short example using 2 chars: AB and BA. AAABBBAAA to be checked. You will need to use QRegExp("(AB|BA)") since the expression cannot search for permutation. So looking for sequences having every element once, requires to have the regex check for (ACGT|ACTG|AGCT|....)
It would be easier to implement something like:
QString seq = "gactacgtccttacgaccaacggcgataaaaattgcccgcataagacaactttcgaggcg";
QMap<QChar,int> count;
void resetCounter()
{
count[QChar('a')] = 0;
count[QChar('c')] = 0;
count[QChar('g')] = 0;
count[QChar('t')] = 0;
}
bool checkCounter()
{
foreach(count.values(), int val)
if(val != 1)
return false;
return true;
}
resetCounter();
for(int i=0; i<seq.length(); i++)
{
count[seq.at(i)] = count[seq.at(i)] + 1;
if(count[seq.at(i)] > 1)
{
resetCounter();
count[seq.at(i)] = 1;
}
if(checkCounter())
{
//Found sequence
count[seq.at(i-3)] = 0;
}
}
Edit: Found small mistake. Have to set current element to 1 after resetCounter() being called

Resources