char - 将 Unicodestring 转换为 Char[]

标签 char c++builder

我有一个包含四个单词行的列表框的表单。
当我单击一行时,应该会在四个不同的文本框中看到这些词。
到目前为止,我已经一切正常,但我在字符转换方面遇到了问题。
列表框中的字符串是 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;  

关于char - 将 Unicodestring 转换为 Char[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12199796/

相关文章:

c++ - 实现 IDropTarget

c++ - 仅初始化部分功能一次

c++ - 无符号字符连接

java - 有没有办法将 java 中的字符串或字符字段转换为数学运算符?

c - 如何从字符数组中提取字符

c - 如何在 C 中将 char 连接到 char*?

c++ - 使用 TRewindReaderProc 倒回 TJSONIterator 类的输入数据

winapi - 如何在 Firemonkey 中获取 TCanvas DC?

带有 vcl 的 C++ : closing secondary form does not end process

c - 如何获得 char * 矩阵?