更改vector中的字符串元素值
Change string element value in vector
我现在正在vector
中与string
合作。我把自己带进了死胡同。我操纵vector<int>
元素,并了解如何与他们一起工作!我知道如何使用string
!但是我无法通过我需要改变向量中的字符串元素值的部分。我的意思是我不知道在loop
中"做点什么"该怎么办。所以简而言之,我把任务交给了我现在工作的人。
从cin
中读取一系列单词,并将值存储在vector
中。在读取所有单词后,处理vector
并将每个单词更改为大写
到目前为止我得到了什么
int main ()
{
vector<string> words; //Container for all input word
string inp; //inp variable will process all input
while (cin>>inp) //read
words.push_back(inp); //Storing words
//Processing vector to make all word Uppercase
for (int i = 0; i <words.size(); ++i)
//do something
words[i]=toupper(i);
for (auto &e : words) //for each element in vector
//do something
cout<<e;
keep_window_open("~");
return 0;
}
第一个for
语句不正确,我尝试访问vector
元素并将单词更改为upper,但它不适合我,它只是示例
我尝试了很多方法来访问vector
元素,但当试图使用string
成员函数toupper()
对vector
我得到混乱的代码和逻辑错误!
谢谢你的宝贵时间。很抱歉我在拼写单词时犯了错误
试试这个:
for (auto& word: words)
for (auto& letter: word)
letter = std::toupper(letter);
这可以通过使用std::transform
标准算法来遍历单词的字符来修复。您也可以使用std::for_each
来代替手动循环。
#include <string>
#include <algorithm>
#include <iostream>
#include <cctype>
#include <vector>
int main()
{
std::vector<std::string> words;
std::string inp;
while (std::cin >> inp)
words.push_back(inp);
std::for_each(words.begin(), words.end(), [] (std::string& word)
{
std::transform(
word.begin(),
word.end(),
word.begin(), (int (&)(int)) std::toupper
);
})
for (auto &e : words)
std::cout << e << std::endl;
}
这里是一个演示
可以在第一个for循环中这样做:
string w = words.at(i);
std::transform(w.begin(), w.end(), w.begin(), ::toupper);
相关文章:
- 是否可以在c++中处理字符串流中的各个元素
- 如何将元素添加到向量的字符串位置
- 如何在 Arduino 字符串的开头添加元素.类似于 JS unshift();
- C++将字符串数组的元素存储到变量中
- 循环访问还包含未使用元素的字符串数组
- 将包含多个元素的字符串作为输入并转换为矢量 C++
- 如何计算字符串中用户输入元素的出现次数?
- C++ 查找字符串中存在的元素向量
- 如何将凯撒密码的元素从字符串更改为字符串
- 常量数组如何在每个元素中只能包含字符,而 char* 数组能够指向每个元素中的字符串?
- 用字符串 c++ 比较对向量的元素
- 将指针作为缓冲区传递到第一个字符串元素
- C++字符串问题-如何访问字符串元素
- 将字符串集合中的元素添加到字符串集合的向量中
- 如何将字符串加载到BYTE*数组(C++)的元素中
- 需要从字符串数组的一部分访问元素
- 如何打印出常量字符串的第一个元素?
- 如何使用libxml2从C 中的XML文件中检索节点和特定元素字符串而不使用XPATH
- 如何使用XPath使用libxml2从C 中的XML文件中检索节点和特定元素字符串
- 添加元素<字符串、指针>以提升无序哈希图