How to delete new-line character in asctime in QString
Solution 1
There are 3 methods you will find useful:
bool QString::endsWith (const QChar &c, Qt::CaseSensitivity cs = Qt::CaseSensitive ) const;
QString::remove(int position, int n);
QString& replace(const QRegExp &rx, const QString & after)
Just remove last character and you're set. You can either use remove()
or replace()
with a regexp detecting \n
at the end of the string.
Please be advised that internally QString
uses 16-bit UTF character encoding.
If you like to operate on 8-bit characters, than you should use QByteArray
and it's QByteArray::remove(int position, int n)
method.
Solution 2
I would use QString::trimmed()
function to remove all trailing and leading whitespace characters, such as '\t', '\n', '\v', '\f', '\r', and ' '. I.e.:
strList = strList.trimmed();
Solution 3
Tell me why you are using C standard API when you use Qt? You have great Qt API to handle dates.
QDateTime time;
uint rawtime = 1430687052;
time.setTime_t(rawtime);
QString humanDate = QLocale::system().toString(time, QLocale::ShortFormat);
To remove newline character in your concept just use QString::trimmed (removes from front and back any white characters).
Solution 4
AS vahancho already pointed out. trimmed is probably the best way to go.
From the documentation of trimmed:
Unlike simplified(), trimmed() leaves internal whitespace alone.
So for example:
QString str = " lots\t of\nwhitespace\r\n ";
str = str.trimmed();
// str == "lots\t of\nwhitespace"
Comments
-
goGud almost 2 years
I am converting time_t to human readable format. For this purpose I am using
asctime()
function. However it is also mentioned in c++ references.The string is followed by a new-line character ('\n') and terminated with a null-character.
I know that I can delete '\n' character if I use char pointer. Such as;
char * str; str(strlen(str)-1) = '\0'; // repleacing new-line char to null-char
However how can I delete new-line characther in QString? Here is my example;
time_t rawtime; struct tm * timeinfo; QString strList; rawtime = 1430687052; timeinfo = localtime (&rawtime); strList += asctime(timeinfo);
EDIT:
I am creating report file, so that I have lots of '\n' char in my
QString
, thats why replacing all '\n' char to null pointer is not good idea. -
goGud almost 9 yearsAs I said in EDIT section, I creating report txt and xls file, that's why deleting all char is not good idea.. My aim is deleting only last '\n' char in QString.
-
goGud almost 9 yearsThank you I used remove function defining QRegExp and it solved my problem.
-
vahancho almost 9 yearsThe function does not delete all chars, but all whitespece chars from the start and the end.
-
goGud almost 9 yearsactually I didnt know Qt has such ability.. I was writing application with limited time, thus I wrote it as fast as possible. +1 for informing such ability.