一、C++输出字符串添加
C++中输出字符串有多种方式,第一种是使用输出运算符”>>”,这种方式可以输出字符串,并且可以和其它变量进行混合输出,示例代码如下:
#include
using namespace std;
int main() {
string str = "hello";
int num = 10;
cout << str << ", " << num << endl;
return 0;
}
这段代码的输出结果是:
hello, 10
第二种方式是使用cout的成员函数write,该函数需要两个参数分别为字符串的首地址和长度,示例代码如下:
#include
#include
using namespace std;
int main() {
string str = "hello";
cout.write(str.c_str(), str.size());
return 0;
}
这段代码的输出结果是:
hello
二、C++输出字符串到文本
我们可以使用文件流将字符串输出到文本文件中,示例代码如下:
#include
#include
using namespace std;
int main() {
ofstream ofs;
ofs.open("test.txt");
ofs << "hello world" << endl;
ofs.close();
return 0;
}
这段代码的输出结果是在程序根目录下生成一个名为test.txt的文件,并且文件中的内容为:
hello world
三、C++输出字符串需要释放吗
C++中的字符串变量是封装了动态分配内存的操作,所以通常不需要我们手动去释放字符串。但是如果使用new操作符手动分配内存,则需要手动释放内存。示例代码如下:
#include
#include
using namespace std;
int main() {
char* str = new char[6];
str[0] = 'h';
str[1] = 'e';
str[2] = 'l';
str[3] = 'l';
str[4] = 'o';
str[5] = '';
cout << str << endl;
delete[] str;
return 0;
}
这段代码输出结果为:
hello
四、C++输出字符串的前18位
我们可以使用string类的成员函数substr来截取子串,示例代码如下:
#include
#include
using namespace std;
int main() {
string str = "abcdefghijklmnopqrstuvwxyz";
string sub = str.substr(0, 18);
cout << sub << endl;
return 0;
}
这段代码输出结果为:
abcdefghijklmnoprr
五、C++输出字符串出现特定字符的次数
我们可以使用algorithm头文件中的count函数来计数,示例代码如下:
#include
#include
#include
using namespace std;
int main() {
string str = "hello world";
char c = 'l';
int count = std::count(str.begin(), str.end(), c);
cout << count << endl;
return 0;
}
这段代码输出结果为:
3
六、C++输出字符串变量
我们可以使用cout输出string类型的变量,示例代码如下:
#include
#include
using namespace std;
int main() {
string str = "hello world";
cout << str << endl;
return 0;
}
这段代码输出结果为:
hello world
七、C++输出字符串中特殊换行符的显示
在字符串中,我们通常使用转义字符”n”来表示换行符,示例代码如下:
#include
#include
using namespace std;
int main() {
string str = "hellonworld";
cout << str << endl;
return 0;
}
这段代码输出结果为:
hello
world
八、C++输出字符串长度
我们可以使用string类的成员函数size来获取字符串的长度,示例代码如下:
#include
#include
using namespace std;
int main() {
string str = "hello world";
cout << str.size() << endl;
return 0;
}
这段代码输出结果为:
11