c ++查找字符串
Program 1:
程序1:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str[] = { "ABC", "PQR", "LMN", "XYZ" };
cout << str[-EOF - EOF];
return 0;
}
Output:
输出:
LMN
Explanation:
说明:
Here, we created an array of strings that contains 4 strings "ABC", "PQR", "LMN" and "XYZ".
在这里,我们创建了一个字符串数组,其中包含4个字符串“ ABC”,“ PQR”,“ LMN”和“ XYZ”。
Consider the below cout statement,
考虑下面的cout语句,
cout<>str[-EOF-EOF];
Here the value of EOF is -1. Then
在这里,EOF的值为-1。 然后
str[-EOF-EOF]
str[--1-1]
str[--2]
str[2]
Then the value of str[2] is "LMN" that will be printed on the console screen.
然后,str [2]的值为“ LMN”,将在控制台屏幕上打印。
Program 2:
程式2:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str[] = { "ABC", "PQR", "LMN", "XYZ" };
int len = 0;
len = (str[1].size() + str[2].length()) / 3;
cout << str[len];
return 0;
}
Output:
输出:
LMN
Explanation:
说明:
Here, we created an array of strings. And a local variable len initialized with 0. In C++, both size() and length() functions are used to get the length of the string in terms of bytes.
在这里,我们创建了一个字符串数组。 还有一个用0初始化的局部变量len。在C ++中, size()和length()函数都用于获取字符串的字节长度。
Let's understand the expression.
让我们了解一下表达式。
len = str[1].size()+str[2].length()/3;
len = (3+3)/3;
len = 6/3;
len = 2;
Then the value of the 2nd index that is "LMN" will be printed on the console screen.
然后, 第二个索引的值“ LMN”将被打印在控制台屏幕上。
Program 3:
程式3:
#include <iostream>
#include <string>
#include <string.h>
using namespace std;
int main()
{
string str[] = { "ABC", "PQR", "LMN", "XYZ" };
int len = 0;
len = strlen((char*)str[2]);
cout << str[len];
return 0;
}
Output:
输出:
main.cpp: In function ‘int main()’:
main.cpp:11:30: error: invalid cast from type ‘std::string {aka std::basic_string}’ to type ‘char*’
len = strlen((char*)str[2]);
^
Explanation:
说明:
It will generate syntax error because the strlen() function cannot get the length of the string object. Here we need to convert a string object into the character array. The c_str() function of string class is used to convert the object of the string into a character array.
由于strlen()函数无法获取字符串对象的长度,因此将产生语法错误。 在这里,我们需要将字符串对象转换为字符数组。 字符串类的c_str()函数用于将字符串的对象转换为字符数组。
So that we need to below statement to find the length of the string.
这样我们就需要在下面的语句中找到字符串的长度。
len = strlen(str[2].c_str());
翻译自: https://www.includehelp.com/cpp-tutorial/strings-find-output-programs-set-2.aspx
c ++查找字符串