编写一段程序,比较两个 std::string 对象。再编写一段程序,比较两个C风格字符串的内容。
时间: 2023-05-12 15:04:09 浏览: 114
比较两个 std::string 对象的程序:
```c++
#include <iostream>
#include <string>
int main() {
std::string str1 = "hello";
std::string str2 = "world";
if (str1 == str2) {
std::cout << "str1 and str2 are equal" << std::endl;
} else {
std::cout << "str1 and str2 are not equal" << std::endl;
}
return 0;
}
```
比较两个C风格字符串的内容的程序:
```c++
#include <iostream>
#include <cstring>
int main() {
char str1[] = "hello";
char str2[] = "world";
if (std::strcmp(str1, str2) == 0) {
std::cout << "str1 and str2 are equal" << std::endl;
} else {
std::cout << "str1 and str2 are not equal" << std::endl;
}
return 0;
}
```
相关问题
#include <iostream>#include <string>int main() { int input; std::cout << "请输入一个数字:"; std::cin >> input; std::string input_str = std::to_string(input); std::string reverse_str(input_str.rbegin(), input_str.rend()); std::cout << "回文数为:" << input_str + reverse_str << std::endl; return 0;}
这是一段用C++编写的程序,主要功能是输入一个数字,然后将该数字与它的反转数相加,输出回文数。
下面是代码的解释和注释:
```c++
#include <iostream> // 引入iostream头文件,用于输入输出
#include <string> // 引入string头文件,用于字符串的操作
int main() {
int input; // 定义一个整型变量input,用于存储输入的数字
std::cout << "请输入一个数字:"; // 提示用户输入数字
std::cin >> input; // 从标准输入流中读取一个整数,并将其存储到input变量中
std::string input_str = std::to_string(input); // 将input转换为字符串类型,并存储到input_str变量中
std::string reverse_str(input_str.rbegin(), input_str.rend()); // 将input_str反转,并存储到reverse_str变量中
// rbegin()和rend()是string类的成员函数,分别表示反向迭代器指向的最后一个字符和第一个字符的前一个位置
std::cout << "回文数为:" << input_str + reverse_str << std::endl; // 将input_str和reverse_str相加,并输出到标准输出流中
// +运算符用于连接两个字符串
return 0; // 返回0,表示程序运行成功
}
```
用C++编写一段程序:输入两个字符串,验证其中一个串是否为另一个的字串。输入:输入两个字符串,每个字符串占一行,长度不超过200且不含空格。输出:若第一个串s1是第二个串s2的子串,输出(s1)is substring of (s2),否则,若第二个串s2是第一个串s1的子串,输出(s2) is substring of (s1),否则,输出 No substring
下面是用C++编写的程序,用于验证一个字符串是否为另一个字符串的子串。
```cpp
#include <iostream>
#include <string>
int main() {
std::string s1, s2;
std::getline(std::cin, s1);
std::getline(std::cin, s2);
if (s1.find(s2) != std::string::npos) {
std::cout << s2 << " is substring of " << s1 << std::endl;
} else if (s2.find(s1) != std::string::npos) {
std::cout << s1 << " is substring of " << s2 << std::endl;
} else {
std::cout << "No substring" << std::endl;
}
return 0;
}
```
请将两个字符串分别输入到程序的标准输入中的两行,然后程序将输出结果。如果第一个字符串是第二个字符串的子串,将输出 "(s1) is substring of (s2)";如果第二个字符串是第一个字符串的子串,将输出 "(s2) is substring of (s1)";如果两个字符串没有子串关系,将输出 "No substring"。