How to apply tolower to a string vector?

1.7k views Asked by At

Since tolower only works for individual characters, how would I use tolower for a string vector? I know I would have to go through each individual character of each item, however I am unsure how to access the individual characters within each item.
eg:-

string vector[Apple, Banana]. 

vector[0] is Apple but I want the character not the whole string. Thanks in advance!

2

There are 2 answers

1
jignatius On

std::transform can help you here to apply tolower to each character in each string inside in your vector:

#include <iostream>
#include <algorithm> // std::transform
#include <string>
#include <vector>


int main()
{
    //Your vector of strings
    std::vector<std::string> fruits = { "Apple", "Banana" };

    //Loop through vector
    for (auto &fruit : fruits)
    {
        //Apply tolower to each character of string
        std::transform(fruit.begin(), fruit.end(), fruit.begin(),
            [](unsigned char c) { return std::tolower(c); });
    }

    for (auto const& fruit : fruits)
        std::cout << fruit << ' ';
}

Demo


As @AlanBirtles suggested you could apply std::transform for the outer loop too. Then it becomes like this:

std::transform(fruits.begin(), fruits.end(), fruits.begin(),
    [](std::string &fruit)
    {
        std::transform(fruit.begin(), fruit.end(), fruit.begin(),
            [](unsigned char c) { return std::tolower(c); });
        return fruit;
    });

Demo

0
Arundeep Chohan On
#include<iostream> 
#include<vector>
#include<string>
using namespace std; 

int main() { 
vector<string> fruits;
fruits.push_back("Apple");
fruits.push_back("Banana");
for(int i = 0; i<fruits.size(); i++){
    for(auto& c : fruits[i])
    {
        c = tolower(c);
    }
    cout << fruits[i] << endl;
}
}

Basically we loop through the character in the vector and make it tolower.