C++代码实现,如果匹配字符串TX,执行1操作,如果匹配字符串RX,执行2操作,,如果匹配字符串Eye,执行3操作
时间: 2024-01-06 18:04:57 浏览: 24
以下是一个简单的 C++ 代码示例,可以实现根据不同的字符串执行不同的操作:
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string input;
cout << "请输入字符串: ";
cin >> input;
if (input == "TX") {
// 执行1操作
cout << "执行1操作" << endl;
} else if (input == "RX") {
// 执行2操作
cout << "执行2操作" << endl;
} else if (input == "Eye") {
// 执行3操作
cout << "执行3操作" << endl;
} else {
// 输入字符串不匹配任何操作
cout << "输入字符串不匹配任何操作" << endl;
}
return 0;
}
```
当用户输入 TX 时,程序会输出“执行1操作”;当用户输入 RX 时,程序会输出“执行2操作”;当用户输入 Eye 时,程序会输出“执行3操作”;当用户输入其他字符串时,程序会输出“输入字符串不匹配任何操作”。
相关问题
c++实现字符串匹配
常见的字符串匹配算法有暴力匹配、KMP算法、Boyer-Moore算法等。
暴力匹配算法思路比较简单,就是从文本串的第一个字符开始,依次与模式串的每个字符进行比较,如果每个字符都相同,则匹配成功;否则继续在文本串中向右移动一个字符,再进行比较,直到匹配成功或者文本串中没有足够的字符与模式串进行比较。
C++实现暴力匹配算法的代码如下:
```c++
#include <iostream>
#include <cstring>
using namespace std;
int brute_force(string text, string pattern) {
int n = text.size();
int m = pattern.size();
for (int i = 0; i <= n - m; i++) {
bool match = true;
for (int j = 0; j < m; j++) {
if (text[i + j] != pattern[j]) {
match = false;
break;
}
}
if (match) {
return i;
}
}
return -1;
}
int main() {
string text = "hello world";
string pattern = "world";
int pos = brute_force(text, pattern);
if (pos == -1) {
cout << "pattern not found" << endl;
} else {
cout << "pattern found at position " << pos << endl;
}
return 0;
}
```
这里使用了两个指针 `i` 和 `j` 分别指向文本串和模式串中正在比较的字符。如果当前字符匹配成功,则两个指针都向右移动一位,否则文本串指针向右移动一位,模式串指针回到开头重新开始匹配。
暴力匹配算法的时间复杂度为 $O(mn)$,其中 $m$ 是模式串长度,$n$ 是文本串长度。在最坏情况下,需要比较 $mn$ 次,因此当模式串比较长时,暴力匹配算法的效率会比较低。
正则匹配字符串c++
以下是使用C++正则表达式匹配字符串的示例代码:
```cpp
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string str = "Hello, world! This is a test string.";
std::regex pattern("test");
if (std::regex_search(str, pattern)) {
std::cout << "Match found." << std::endl;
} else {
std::cout << "Match not found." << std::endl;
}
return 0;
}
```
上述代码中,我们首先定义了一个字符串`str`和一个正则表达式`pattern`,然后使用`std::regex_search`函数在字符串中查找是否有与正则表达式匹配的子串。如果找到了匹配的子串,则输出`Match found.`,否则输出`Match not found.`。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)