c++ string 对比字符串是否相等
时间: 2023-07-21 10:30:18 浏览: 51
在 C++ 中,可以使用 `==` 运算符来比较两个字符串是否相等。例如:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "hello";
string str2 = "world";
if (str1 == str2) {
cout << "str1 and str2 are equal" << endl;
} else {
cout << "str1 and str2 are not equal" << endl;
}
return 0;
}
```
输出结果为:
```
str1 and str2 are not equal
```
相关问题
c++比较字符串是否相等
在 C++ 中比较字符串是否相等,可以使用字符串类的 compare() 函数或者直接使用运算符 "=="。例如:
```
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "hello";
string str2 = "world";
// 使用 compare() 函数比较字符串是否相等
if (str1.compare(str2) == 0) {
cout << "str1 and str2 are equal" << endl;
} else {
cout << "str1 and str2 are not equal" << endl;
}
// 使用运算符 "==" 比较字符串是否相等
if (str1 == str2) {
cout << "str1 and str2 are equal" << endl;
} else {
cout << "str1 and str2 are not equal" << endl;
}
return 0;
}
```
输出结果:
```
str1 and str2 are not equal
str1 and str2 are not equal
```
c++string截取字符串
### 回答1:
在C++中,可以使用`substr()`函数来截取字符串。该函数接受两个参数,第一个参数是起始位置,第二个参数是截取的长度。例如,以下代码截取字符串`s`的从第3个字符开始的4个字符:
```c++
std::string s = "Hello, world!";
std::string sub = s.substr(2, 4); // sub = "llo,"
```
注意,第一个字符的索引是0,因此第3个字符的索引是2。如果第二个参数缺省,则截取从起始位置到字符串结尾的所有字符。例如,以下代码截取字符串`s`的从第3个字符开始到结尾的所有字符:
```c++
std::string s = "Hello, world!";
std::string sub = s.substr(2); // sub = "llo, world!"
```
### 回答2:
C语言中可以使用库函数来截取字符串,常用的库函数有`strcpy`、`strncpy`和`strncat`。
首先是`strcpy`函数,它用于将源字符串拷贝到目标字符串中,语法如下:
```c
char *strcpy(char *dest, const char *src);
```
其中,`dest`是目标字符串,`src`是源字符串。这个函数会将源字符串中的字符拷贝到目标字符串中,直到遇到空字符`\0`为止。
接下来是`strncpy`函数,它用于将指定长度的源字符串拷贝到目标字符串中,语法如下:
```c
char *strncpy(char *dest, const char *src, size_t n);
```
其中,`dest`是目标字符串,`src`是源字符串,`n`是要拷贝的字符个数。如果源字符串的长度小于`n`,则会将剩余的部分用空字符填充。
最后是`strncat`函数,它用于将一个字符串连接到另一个字符串的末尾,语法如下:
```c
char *strncat(char *dest, const char *src, size_t n);
```
其中,`dest`是目标字符串,`src`是要连接的源字符串,`n`是要连接的字符个数。这个函数会将源字符串中的字符连接到目标字符串的末尾。
通过调用这些库函数,我们可以实现字符串的截取操作。比如,如果要截取一个字符串的前5个字符,可以使用`strncpy`函数,将前5个字符拷贝到一个新的字符串中即可。
需要注意的是,在进行字符串截取操作时,需要保证目标字符串足够大,以免发生溢出。此外,还需要在截取后的目标字符串末尾添加空字符`\0`,以保证字符串的完整性。
### 回答3:
C++中的字符串截取可以通过使用`substr()`函数来实现。`substr()`函数需要两个参数,第一个参数是起始索引位置,第二个参数是要截取的字符个数。
例如,如果我们有一个字符串`str = "Hello, World!"`,我们可以使用`substr()`函数来截取从索引位置为7的字符开始的5个字符,即`str.substr(7, 5)`。这将返回一个新的字符串"World"。
另外,如果我们只指定起始索引位置而不指定要截取的字符个数,`substr()`函数将返回从指定索引位置到字符串末尾的所有字符。例如,`str.substr(7)`将返回"World!"。
需要注意的是,C++中字符串的索引位置是从0开始的。也就是说,字符串的第一个字符的索引位置是0,第二个字符的索引位置是1,依此类推。
此外,我们还可以使用字符串的[]运算符来截取单个字符。例如,`str[0]`将返回字符串中的第一个字符。
总结来说,C++中可以通过`substr()`函数和[]运算符来截取字符串。使用`substr()`函数我们可以指定起始索引和截取字符个数来得到一个新的子字符串,使用[]运算符我们可以直接获取字符串中的单个字符。