C++一个字符串按空格分割存入数组中
时间: 2024-03-22 14:42:12 浏览: 107
可以使用stringstream和getline函数来实现将一个字符串按空格分割存入数组中,示例代码如下:
```cpp
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
int main() {
string str = "hello world how are you";
vector<string> arr;
stringstream ss(str);
string token;
while (getline(ss, token, ' ')) {
arr.push_back(token);
}
for (int i = 0; i < arr.size(); i++) {
cout << arr[i] << endl;
}
return 0;
}
```
运行结果:
```
hello
world
how
are
you
```
相关问题
c++ 判断字符串是否在一个数组中
如果要判断一个字符串是否在一个数组中,可以使用 C 语言中的 `strcmp` 函数。
该函数的原型为:
```c
int strcmp(const char *s1, const char *s2);
```
它接受两个参数:两个字符串的地址。如果两个字符串相等,则返回 0,否则返回一个非 0 值。
你可以使用这个函数来遍历数组,然后将要判断的字符串和数组中的每一个元素进行比较,如果返回值为 0,则说明这个字符串在数组中。
下面是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char *strings[] = {"abc", "def", "ghi"};
char *target = "abc";
int found = 0;
for (int i = 0; i < 3; i++) {
if (strcmp(strings[i], target) == 0) {
found = 1;
break;
}
}
if (found) {
printf("The string was found in the array.\n");
} else {
printf("The string was not found in the array.\n");
}
return 0;
}
```
该程序将遍历字符串数组 `strings`,并判断字符串 `target` 是否在数组中。如果找到,则输出 "The string was found in the array.",否则输出 "The string was not found in the array."。
c++如何根据逗号把一个字符串分割为字符串数组
在 C++ 中,可以使用 std::stringstream 和 std::getline 函数来根据逗号将一个字符串分割为字符串数组。下面是示例代码:
```cpp
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
int main() {
std::string str = "apple,orange,banana";
std::vector<std::string> tokens;
std::stringstream ss(str);
std::string token;
while (std::getline(ss, token, ',')) {
tokens.push_back(token);
}
for (const auto& token : tokens) {
std::cout << token << std::endl;
}
return 0;
}
```
在这个示例中,我们首先定义了一个包含逗号分隔符的字符串 str,然后创建了一个 std::stringstream 对象来读取输入字符串。
然后,我们使用 std::getline 函数从 std::stringstream 对象中读取每个逗号分隔的标记,并将其添加到一个 std::vector<std::string> 对象中。
最后,我们遍历 std::vector<std::string> 对象,并打印每个标记。