一、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] = '\0';
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 = "hello\nworld";
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
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/154129.html