C++ 打印在给定字符串中出现的给定数组中的所有字符串
在编程世界中,有许多场景我们都希望能够在更大的文本中寻找特定的模式。其中一个常见的任务是在给定字符串中找到并打印出给定数组中出现的所有字符串。这个看似基本的问题可以使用各种方法来解决,在本文中,我们将探讨其中的两种方法。我们将对每种方法使用的语法和算法进行详细解释,并附带两个完整可执行的代码示例。
语法
在我们进入具体方法之前,让我们先了解一下解决这个问题所使用的语法:
void printMatchingStrings(string array[], string text);
步骤
为了解决在给定字符串中查找和打印数组中的所有子字符串的问题,我们可以按照以下逐步算法进行:
- 初始化一个空向量来存储匹配的字符串。
-
遍历数组中的每个字符串。
-
检查当前字符串是否是给定文本的子字符串。
-
如果是,则将该字符串添加到匹配字符串的向量中。
-
在遍历完所有字符串后,打印匹配字符串的向量。
方法1:使用string.find()函数
在这种方法中,我们将使用string.find()函数,它返回字符串中子字符串的位置。如果未找到子字符串,则返回一个特殊值string::npos。
示例
#include <iostream>
#include <vector>
#include <string>
void printMatchingStrings(const std::string array[], const std::string& text, int arraySize) {
std::vector<std::string> matchingStrings;
for (int i = 0; i < arraySize; i++) {
if (text.find(array[i]) != std::string::npos) {
matchingStrings.push_back(array[i]);
}
}
for (const std::string& match : matchingStrings) {
std::cout << match << std::endl;
}
}
int main() {
const std::string array[] = { "apple", "banana", "orange", "pear" };
const std::string text = "I like to eat bananas and oranges.";
int arraySize = sizeof(array) / sizeof(array[0]);
printMatchingStrings(array, text, arraySize);
return 0;
}
输出
banana
orange
方法2:使用正则表达式
正则表达式提供了一种强大的工具,用于在字符串中匹配模式。我们也可以利用它们来解决我们的问题。
示例
#include <iostream>
#include <vector>
#include <string>
#include <regex>
void printMatchingStrings(const std::string array[], const std::string& text, int arraySize) {
std::vector<std::string> matchingStrings;
for (int i = 0; i < arraySize; i++) {
std::regex pattern(array[i]);
if (std::regex_search(text, pattern)) {
matchingStrings.push_back(array[i]);
}
}
for (const std::string& match : matchingStrings) {
std::cout << match << std::endl;
}
}
int main() {
const std::string array[] = { "apple", "banana", "orange", "pear" };
const std::string text = "I like to eat bananas and pear.";
int arraySize = sizeof(array) / sizeof(array[0]);
printMatchingStrings(array, text, arraySize);
return 0;
}
输出
banana
pear
选择正确的方法
这两种方法的选择取决于具体问题的需求
使用string.find()方法
要匹配的模式相对简单。
性能是一个问题,因为对于简单的模式,string.find()方法可能比正则表达式更快。
你更喜欢不需要正则表达式语法的更简单的实现。
使用正则表达式方法if
要匹配的模式是复杂的,需要高级的模式匹配特征。
模式匹配的灵活性和强大性是非常重要的。
性能不是关键因素,模式的复杂性也证明使用正则表达式是合理的。
结论
在本文中,我们探讨了两种独特的方法来解决从数组中找到并打印出作为给定字符串中的子字符串出现的所有字符串的问题。主要方法使用了string.find()函数,这是一个简单直接的解决方案。随后的方法利用了正则表达式的强大功能来处理更复杂的模式匹配情况。根据您特定问题的需求,您可以选择最合适的方法。请记住,模式匹配是编程中的一项基本任务,对各种方法和策略有强大的理解能够显著提升您的问题解决能力。所以下次遇到类似的问题时,您将有能力有效地处理它。
极客笔记