我正在尝试使用c_str()将c++字符串对象转换为C风格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 ' ' i.e. null
while( ptr != ' ')
{
cout << "*ptr : "<< *ptr << endl;
ptr++;
}
return 0;
}
但似乎它没有在末尾添加' ',循环也没有终止。我哪里错了?
c风格字符串(例如char* st="Alpha";)可以用代码中所示的循环访问,但是当从字符串对象转换为c风格字符串时,它不能。我该怎么做呢?
while( ptr != ' ')
应该while (*ptr != ' ')
我想你这里少了一个星号:
while( ptr != ' ')
使它
while( *ptr != ' ')
您还可以像这样访问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风格字符串中的null终止字符,但如果您有自己的选择,请保留std::string.
应该是
while( *ptr != ' ')
{
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]
等
这很好。谢谢你的回复。
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 != ' ')
{
cout << "*ptr : "<< *ptr << endl;
ptr++;
}
return 0;
}