Удаление непечатаемых символов Юникода из TChar * - PullRequest
0 голосов
/ 06 сентября 2018

У меня есть tchar* со строкой The system time has changed to ‎2018‎ - ‎09‎ - ‎06T15:13 : 52.257364700Z from ‎2018‎ - ‎09‎ - ‎06T15 : 13 : 52.257364700Z.

Когда я помещаю эту строку здесь Я вижу символы вокруг значений моей даты, и когда я печатаю ее, используя wPrintf, я получаю знаки вопроса в этих местах.

Есть ли способ перебирать tchar* и удалять не-ASCII символы?

int main() {
    const TCHAR *pText = _T("The system time has changed to ‎2018‎ - ‎09‎ - ‎06T15:13 : 52.257364700Z from ‎2018‎ - ‎09‎ - ‎06T15 : 13 : 52.257364700Z.");
    TCHAR* temp;
    temp = removet((TCHAR*)pText, _tcslen(pText)); 

    wprintf(_T("%s"), temp);
}

TCHAR* removet(TCHAR* text, int len) {
    int offset = 0;
    for (int i = 0; text[i] != 0; ++i) {

        if (text[i] > 127) {
            offset++;
        }
        if (!((i + offset) > len)) {
            wprintf(_T("%d"), i +offset);
            text[i] = text[i + offset];
        }
   }
   return text;
}

Исправленный код:

int main() {
    const TCHAR *pText = _T("The system time has changed to ‎2018‎ - ‎09‎ - ‎06T15:13 : 52.257364700Z from ‎2018‎ - ‎09‎ - ‎06T15 : 13 : 52.257364700Z.");
    TCHAR* temp;
    temp = removet((TCHAR*)pText, _tcslen(pText)); 

    wprintf(_T("%s"), temp);
}

TCHAR* removet(TCHAR* text, int len) {
    int offset = 0; 
    TCHAR* str2 = new TCHAR[len+1];
    _tcscpy_s(str2, len+1, text);
    for (int i = 0; str2[i] != 0; ++i) {

        if (str2[i+offset] > 127) {
            offset++;
        }
        if (!((i + offset) >= len)) {
           str2[i] = str2[i + offset];
        }
    }
    return str2;
}

1 Ответ

0 голосов
/ 06 сентября 2018

Если бы вы использовали std::string вместо необработанных массивов символов, это было бы проще, но вы все равно можете использовать некоторые функции c ++:

#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>

int main()
{
    tchar* test = new tchar[100];
    _tcscpy(test, _T("test string 1235"));
    tchar* end = std::remove_if(test, test + _tcslen(test), [](tchar ch){ return ch >= 127;} );
    *end = '\0';
    std::cout << test << "\n";
}

И используя std::basic_string:

#include <iostream>
#include <string>
#include <algorithm>

int main()
{
    std::basic_string<tchar> test = _T("test string 1235");
    auto end = std::remove_if(test.begin(), test.end(), [](tchar ch){ return ch >= 127;} );
    test.erase(end, test.end());
    std::cout << test << "\n";
}
...