正在将Unicodestring转换为Char[]



我有一个带有Listbox的表单,它包含四行单词。当我点击一行时,这些单词应该出现在四个不同的文本框中。到目前为止,我已经完成了所有工作,但我在字符转换方面遇到了问题。

列表框中的字符串是UnicodeString,但strtok使用了char[]。编译器告诉我;无法将UnicodeString转换为Char[]"。这是我正在使用的代码:

{
 int a;
 UnicodeString b;
 char * pch;
 int c;
 a=DatabaseList->ItemIndex;   //databaselist is the listbox
 b=DatabaseList->Items->Strings[a]; 
 char str[] = b; //This is the part that fails, telling its unicode and not char[].
 pch = strtok (str," ");      
 c=1;                          
 while (pch!=NULL)
    {
       if (c==1)
       {
          ServerAddress->Text=pch;
       } else if (c==2)
       {
          DatabaseName->Text=pch;
       } else if (c==3)
       {
          Username->Text=pch;
       } else if (c==4)
       {
          Password->Text=pch;
       }
       pch = strtok (NULL, " ");
       c=c+1;
    }
}

我知道我的代码看起来不太好,实际上相当糟糕。我只是在用C++学习一些编程。

如何转换?

strtok实际上修改了您的char数组,因此您需要构造一个允许修改的字符数组。直接引用到UnicodeString字符串将不起作用。

// first convert to AnsiString instead of Unicode.
AnsiString ansiB(b);  
// allocate enough memory for your char array (and the null terminator)
char* str = new char[ansiB.Length()+1];  
// copy the contents of the AnsiString into your char array 
strcpy(str, ansiB.c_str());  
// the rest of your code goes here
// remember to delete your char array when done
delete[] str;  

这对我有效,并节省了我转换到AnsiString 的时间

// Using a static buffer
#define MAX_SIZE 256
UnicodeString ustring = "Convert me";
char mbstring[MAX_SIZE];
    wcstombs(mbstring,ustring.c_str(),MAX_SIZE);
// Using dynamic buffer
char *dmbstring;
    dmbstring = new char[ustring.Length() + 1];
    wcstombs(dmbstring,ustring.c_str(),ustring.Length() + 1);
    // use dmbstring
    delete dmbstring;

最新更新