I have Long String with meaningful sentences in it. I want split it by given number of chars a part will hold without breaking the last word of part.
I wrote an algo which is splitting string fine but the words in parts are getting mixed up and are being placed in random location.
My code:
QString str = "कोरोना वायरस के संक्रमण से स्पेन में शुक्रवार 932 लोगों की मौत हुई. इसके साथ ही स्पेन में मरने वालों की कुल
संख्या 10 हज़ार 935 पहुंच गई है. इटली के बाद स्पेन दुनिया का दूसरा देश है जहां कोरोना वायरस से सबसे ज़्यादा मौतें हुई हैं.";
int m = 30;
QStringList words = str.split(" ");
QStringList result;
while(words.isEmpty()==false){
QString strPart;
if(QString(words.join(" ")).length()>m){
for (int i = 0; i < words.count(); i++) {
if(strPart.count()<m){
strPart.append(words.at(i)+" ");
words.removeAt(i);
}
}
}else if(QString(words.join(" ")).length()<m){
for (int i = 0; i < words.count(); i++) {
strPart.append(words.join(" "));
words.clear();
}
}
result.append(strPart);
}
qDebug() <<result;
and the result in debug is :
("कोरोना के से में 932 की हुई. साथ ", "वायरस स्पेन लोगों इसके स्पेन मरने ", "संक्रमण मौत में की संख्या हज़ार ", "शुक्रवार वालों 10 पहुंच है. के ", "ही 935 इटली स्पेन का देश जहां ", "कुल बाद दूसरा कोरोना से ज़्यादा ", "गई है सबसे हुई ", "दुनिया वायरस मौतें हैं.")
Any help will be appreciated. I found a python code for doing same thing but am not able to port it to c++
Based on @scheff suggestion the solution proposed by him of adding --i
to update value of i
in first for loop works final code is given below for future.
QString str = "कोरोना वायरस के संक्रमण से स्पेन में शुक्रवार 932 लोगों की मौत हुई. इसके साथ ही स्पेन में मरने वालों की कुल
संख्या 10 हज़ार 935 पहुंच गई है. इटली के बाद स्पेन दुनिया का दूसरा देश है जहां कोरोना वायरस से सबसे ज़्यादा मौतें हुई हैं.";
int m = 30;
QStringList words = str.split(" ");
QStringList result;
while(words.isEmpty()==false){
QString strPart;
if(QString(words.join(" ")).length()>m){
for (int i = 0; i < words.count(); i++) {
if(strPart.count()<m){
strPart.append(words.at(i)+" ");
words.removeAt(i);
--i; // updated here
}
}
}else if(QString(words.join(" ")).length()<m){
strPart.append(words.join(" "));
words.clear();
}
result.append(strPart);
}
qDebug() <<result;