将字符串转换为c风格字符串并检测空终止字符
Converting string to c-style string and detecting null terminating character
我正在尝试使用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;
}
相关文章:
- 从 argv[1] 转换为字符 * 字符串后有什么问题?
- 将 NULL 与 C 的字符* 字符串一起使用
- 无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
- 无法将常量字符字符串传递给模板类
- 如何组合一个宽字符字符串,中间插入一些空字符
- 如何将二维数组类型字符(字符串)作为函数参数传递?
- 从给定索引返回子字符字符串的函数
- 字符 [](c 字符串)的初始化标准
- 如何将字符字符串用作数学运算符
- 将 Unicode 字符/字符串写入文件
- C++,字符* 字符串修改
- 如何有效地用不同的整数元素替换字符字符串的元素
- C++:如果我们在字符串中添加一些整数,为什么它会从开头删除该数量的字符?(字符串 + 整数)
- strcpy正在复制sth字符i字符串.如何解决此错误
- 在C++中将双精度转换为字符*/字符串
- C 中的宽字符字符串
- 如何提取C 中的字符/字符串之间的字符串
- 无法将字符/字符串转换为int
- 带有指针的反转字符字符串
- 反转字符串中的 n 个字符(字符串中没有空格),而不使用 c++ 中的内置函数