将字符串转换为c样式字符串并检测空终止字符

时间:2013-04-16 11:51:45

标签: c++

我正在尝试使用c_str()将C ++字符串对象转换为C-Style NULL终止字符串,然后尝试访问单个字符,因为它可以为c样式字符串完成。

#include <iostream>
#include <string>

using namespace std;

int main()
{
   string str1("Alpha");
   cout << str1 << endl;

   const char * st = new char [str1.length()+1];
   st = str1.c_str(); // Converts to null terminated string

   const char* ptr=st;

   // Manually Showing each character
   // correctly shows each character

   cout << *ptr << endl;
   ptr++;
   cout << *ptr << endl;
   ptr++;
   cout << *ptr << endl;
   ptr++;
   cout << *ptr << endl;
   ptr++;
   cout << *ptr << endl;
   ptr++;
   cout << "# Null Character :" << *ptr << endl;

   // But below loop does not terminate
   // It does not find '\0' i.e. null

   while( ptr != '\0')
   {
      cout << "*ptr : "<< *ptr << endl;
      ptr++;
   }
   return 0;
}

但似乎它不会在末尾添加'\ 0'并且循环不会终止。 我哪里错了?

C风格的字符串(例如char * st =“Alpha”;)可以通过代码中显示的循环访问,但是当从字符串对象转换为c风格的字符串时,它就不能。我该怎么做它?

4 个答案:

答案 0 :(得分:4)

while( ptr != '\0')

应该是

while (*ptr != '\0')

答案 1 :(得分:4)

我认为你在这里错过了一个星号:

while( ptr != '\0')

使其成为

while( *ptr != '\0')

您还可以像这样访问string的每个元素:

string helloWorld[2] = {"HELLO", "WORLD"};
char c = helloWorld[0][0];
cout << c;

您还可以迭代string

string str ("Hello World");
string::iterator it;
for (int index = 0, it = str.begin() ; it < str.end(); ++it)
   cout << index++ << *it;

string str ("Hello World");
string::iterator it;
for (int index = 0, it = str.begin() ; it < str.end(); ++it, ++index)
   cout << index << *it;

string str ("Hello World");
string::iterator it;
int index = 0;
for (it = str.begin() ; it < str.end(); ++it, ++index)
   cout << index << *it;

了解您正在寻找C风格字符串中的空终止字符,但如果您有您的druthers,请使用std :: string。

答案 2 :(得分:4)

应该是

    while( *ptr != '\0')
        {
            cout << "*ptr : "<< *ptr << endl;
            ptr++;
    }

    const char * st = new char [str1.length()+1];
    st=str1.c_str();//Converts to null terminated String

应该是

    char * st = new char [str1.length()+1];
    strcpy(st, str1.c_str());//Copies the characters

或者可能是

    const char * st = str1.c_str();//Converts to null terminated String

你的版本是两者的混合,因为它分配内存就像它将复制字符一样,但是不会复制任何内容。

您是否意识到您也可以访问std::string的个别字符?只需str1[0]str1[1]str1[i]

答案 3 :(得分:0)

这很好..感谢您的回复。

 int main()
    {
        string str1("Alpha");
            cout << str1 << endl;




        const char * st = new char [str1.length()+1];
            st=str1.c_str();
           //strcpy(st, str1.c_str());//Copies the characters
           //throws error:
           //Test.cpp:19: error: invalid conversion from `const char*' to `char*'
           //Test.cpp:19: error:   initializing argument 1 of `char* strcpy(char*, const char*)'

            const char* ptr=st;


            while( *ptr != '\0')
                {
                    cout << "*ptr : "<< *ptr << endl;
                    ptr++;
            }
        return 0;
        }