c++判断字符在字符串
时间: 2023-12-04 18:01:55 浏览: 49
在 C++ 中,可以使用标准库函数 `std::string::find` 来判断一个字符是否在一个字符串中出现过。该函数的用法如下:
```cpp
#include <string>
int main() {
std::string str = "hello world";
char ch = 'o';
if (str.find(ch) != std::string::npos) {
// 字符 ch 在字符串 str 中出现过
}
return 0;
}
```
其中,`std::string::find` 函数返回字符在字符串中第一次出现的位置,如果字符没有在字符串中出现过,则返回 `std::string::npos`。因此,可以通过判断返回值是否等于 `std::string::npos` 来判断字符是否在字符串中出现过。
相关问题
c++判断字符串是否相等
在C语言中,要判断两个字符串是否相等,可以使用strcmp函数进行比较。strcmp函数会逐个比较两个字符串的字符,直到出现不同的字符或遇到字符串结束符'\0'。如果两个字符串相等,strcmp函数返回0;如果不相等,返回非0值。
示例代码如下:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "hello";
char str2[] = "world";
if (strcmp(str1, str2) == 0) {
printf("两个字符串相等\n");
} else {
printf("两个字符串不相等\n");
}
return 0;
}
```
输出结果为:"两个字符串不相等"
C++判断字符串是否为空
要判断一个字符串是否为空,可以使用字符串的`empty()`函数或者`length()`函数来判断字符串的长度是否为0。下面是一个示例代码:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "";
if (str.empty()) {
std::cout << "字符串为空" << std::endl;
} else {
std::cout << "字符串不为空" << std::endl;
}
return 0;
}
```
在这个示例中,我们创建了一个空字符串`str`。然后使用`empty()`函数判断字符串是否为空,如果为空,则输出"字符串为空",否则输出"字符串不为空"。你也可以使用`length()`函数来判断字符串长度是否为0,效果是一样的。