给定一个字符串数组,打印数组中的所有词。请用C++代码实现
时间: 2023-02-24 19:16:53 浏览: 133
以下是用 C 语言实现的代码:
```
#include <stdio.h>
int main()
{
char *words[] = {"hello", "world", "goodbye"};
int size = sizeof(words)/sizeof(words[0]);
for (int i = 0; i < size; i++)
{
printf("%s\n", words[i]);
}
return 0;
}
```
该代码定义了一个字符串数组 `words`,其中包含三个字符串,然后通过循环打印数组中的每个字符串。
相关问题
给定一个字符串s和一个字符串数组words,编写一个程序查找字符串s中是否有任意一个字符串数组中的单词。用map实现
好的,您的问题是关于字符串匹配的。以下是使用C++语言和map数据结构实现的代码示例:
```cpp
#include <iostream>
#include <string>
#include <map>
using namespace std;
bool hasWord(string s, string words[], int n) {
map<string, bool> m; // 使用map记录字符串数组中的单词
for (int i = 0; i < n; i++) {
m[words[i]] = true;
}
string word = ""; // 用于暂存当前已匹配的单词
for (int i = 0; i < s.length(); i++) {
if (s[i] == ' ') { // 如果遇到空格,说明已匹配一个单词
if (m.find(word) != m.end()) { // 在map中查找该单词是否在字符串数组中
return true; // 如果在,则找到了一个匹配的单词,返回true
}
word = ""; // 清空word,准备匹配下一个单词
} else {
word += s[i]; // 将字符加入word中
}
}
if (m.find(word) != m.end()) { // 处理最后一个单词
return true;
}
return false; // 如果没有找到匹配的单词,则返回false
}
int main() {
string s = "This is a test string.";
string words[] = {"test", "string", "apple", "banana"};
int n = sizeof(words) / sizeof(words[0]);
if (hasWord(s, words, n)) {
cout << "Found a matching word." << endl;
} else {
cout << "No matching word found." << endl;
}
return 0;
}
```
这个代码示例的题意是给定一个字符串s和一个字符串数组words,判断s中是否包含任意一个字符串数组中的单词。具体实现是使用map数据结构记录字符串数组中的单词,然后遍历字符串s,逐个匹配单词并在map中查找是否存在。如果找到了一个匹配的单词,则返回true。最后,如果没有找到匹配的单词,则返回false。
c++ 实现在给定字符串中搜索并返回子字符串个数的函数
可以使用字符串查找算法来实现在给定字符串中搜索并返回子字符串个数的函数。比较常用的算法是KMP算法和Boyer-Moore算法。
下面是使用KMP算法实现的代码示例:
```cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<int> getNext(const string& pattern) {
int n = pattern.length();
vector<int> next(n, 0);
for (int i = 1, j = 0; i < n; i++) {
while (j > 0 && pattern[i] != pattern[j]) {
j = next[j - 1];
}
if (pattern[i] == pattern[j]) {
j++;
}
next[i] = j;
}
return next;
}
int countSubstring(const string& str, const string& pattern) {
int n = str.length(), m = pattern.length();
vector<int> next = getNext(pattern);
int res = 0;
for (int i = 0, j = 0; i < n; i++) {
while (j > 0 && str[i] != pattern[j]) {
j = next[j - 1];
}
if (str[i] == pattern[j]) {
j++;
}
if (j == m) {
res++;
j = next[j - 1];
}
}
return res;
}
int main() {
string str = "aabaaabaaac";
string pattern = "aa";
int count = countSubstring(str, pattern);
cout << count << endl; // 输出 4
return 0;
}
```
在上面的代码中,`getNext`函数用来计算模式串的next数组,`countSubstring`函数用来计算字符串中子串的个数。具体实现过程中,我们需要两个指针i和j,分别指向字符串和模式串。当str[i]和pattern[j]不匹配时,我们需要用next数组来更新j的值,直到str[i]和pattern[j]匹配为止。当j等于模式串的长度时,说明找到了一个匹配的子串,此时将结果加1,并更新j的值为next[j-1]。