本文共 3170 字,大约阅读时间需要 10 分钟。
c ++查找字符串
Program 1:
程序1:
#include#include using namespace std;int main(){ string str = "includehelp"; for (int i = 0; i < str.length(); i++) { cout << str.at(i) - 32 << " "; } return 0;}
Output:
输出:
73 78 67 76 85 68 69 72 69 76 80
Explanation:
说明:
Here, we created a string str initialized with "includehelp" and we create a character variable ch.
在这里,我们创建了一个用“ includehelp”初始化的字符串str ,并创建了一个字符变量ch。
Here, we accessed character index-wise from string str, and we subtract each character by 32. Then
在这里,我们从字符串str逐个索引地访问字符,然后将每个字符减去32。然后
The subtracted ASCII value will print on the console screen, because ASCII value of 'i' is 105 and after subtraction value will be 73, similarly each individual's ASCII value is subtracted by 32 and print on the console screen.
减去的ASCII值将打印在控制台屏幕上,因为ASCII值“ i”为105,而减值后为73,类似地,每个人的ASCII值都减去32,然后打印在控制台屏幕上。
Program 2:
程式2:
#include#include using namespace std;int main(){ string str = ""; str.push_back('i'); str.push_back('n'); str.push_back('c'); str.push_back('l'); str.push_back('u'); str.push_back('d'); str.push_back('e'); str.push_back('h'); str.push_back('e'); str.push_back('l'); str.push_back('p'); for (int i = 0; i < str.length(); i++) { cout << str[i] << " "; } return 0;}
Output:
输出:
i n c l u d e h e l p
Explanation:
说明:
Here, we created the string object str. We used push_back() member function of string class to insert the item into the string, here we added "i n c l u d e h e l p" string using push_back() function and print string character-wise using the for loop on the console screen.
在这里,我们创建了字符串对象str 。 我们使用了字符串类的push_back()成员函数将项目插入到字符串中,这里我们使用push_back()函数添加了“ includehelp”字符串,并在控制台屏幕上使用了for循环以字符方式打印了字符串。
Program 3:
程式3:
#include#include using namespace std;int main(){ string str = ""; str.push_back('i'); str.push_back('n'); str.push_back('c'); str.push_back('l'); str.push_back('u'); str.push_back('d'); str.push_back('e'); str.push_front('h'); str.push_front('e'); str.push_front('l'); str.push_front('p'); for (int i = 0; i < str.length(); i++) { cout << str[i] << " "; } return 0;}
Output:
输出:
main.cpp: In function ‘int main()’:main.cpp:17:9: error: ‘std::string {aka class std::basic_string}’ has no member named ‘push_front’; did you mean ‘push_back’? str.push_front('h'); ^~~~~~~~~~main.cpp:18:9: error: ‘std::string {aka class std::basic_string}’ has no member named ‘push_front’; did you mean ‘push_back’? str.push_front('e'); ^~~~~~~~~~main.cpp:19:9: error: ‘std::string {aka class std::basic_string}’ has no member named ‘push_front’; did you mean ‘push_back’? str.push_front('l'); ^~~~~~~~~~main.cpp:20:9: error: ‘std::string {aka class std::basic_string}’ has no member named ‘push_front’; did you mean ‘push_back’? str.push_front('p'); ^~~~~~~~~~
Explanation:
说明:
It will generate compilation errors because the push_front() function is not available in the string class.
由于push_front()函数在字符串类中不可用,因此将生成编译错误。
翻译自:
c ++查找字符串
转载地址:http://vsvzd.baihongyu.com/