C++ 判断字符串前两个字符是否为51
时间: 2023-08-06 11:07:00 浏览: 44
可以使用字符串的 substr 函数获取前两个字符,再将其转换成整型进行判断。示例代码如下:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "512345";
int num = stoi(str.substr(0, 2)); // 获取前两个字符并转换成整型
if (num == 51) {
cout << "前两个字符为51" << endl;
} else {
cout << "前两个字符不为51" << endl;
}
return 0;
}
```
输出结果为:
```
前两个字符为51
```
相关问题
c++ 判断字符串是否为回文
以下是使用C++判断字符串是否为回文的两种方法:
方法一:使用双指针法
```cpp
#include <iostream>
#include <string>
using namespace std;
bool isPalindrome(string s) {
int left = 0;
int right = s.length() - 1;
while (left < right) {
if (s[left] != s[right]) {
return false;
}
left++;
right--;
}
return true;
}
int main() {
string str;
cout << "请输入一个字符串:";
cin >> str;
if (isPalindrome(str)) {
cout << str << "是回文串" << endl;
} else {
cout << str << "不是回文串" << endl;
}
return 0;
}
```
方法二:使用reverse()函数
```cpp
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool isPalindrome(string s) {
string reversed = s;
reverse(reversed.begin(), reversed.end());
if (s == reversed) {
return true;
} else {
return false;
}
}
int main() {
string str;
cout << "请输入一个字符串:";
cin >> str;
if (isPalindrome(str)) {
cout << str << "是回文串" << endl;
} else {
cout << str << "不是回文串" << endl;
}
return 0;
}
```
c++判断两个字符串是否相等
在 C++ 中,可以使用字符串类 string 的 compare() 或者 == 运算符来比较两个字符串是否相等。
例如,可以使用以下代码判断两个字符串 str1 和 str2 是否相等:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "hello";
string str2 = "world";
if (str1 == str2) {
cout << "str1 equals str2" << endl;
} else {
cout << "str1 does not equal str2" << endl;
}
return 0;
}
```
也可以使用 compare() 方法:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "hello";
string str2 = "world";
if (str1.compare(str2) == 0) {
cout << "str1 equals str2" << endl;
} else {
cout << "str1 does not equal str2" << endl;
}
return 0;
}
```
以上两种方法都可以判断两个字符串是否相等。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)