0

How do I uppercase for example letter "i"? I tried transform, convert. Now, I think using a for loop may be the best option, but cannot seem to figure it out!

#include <iostream>
#include <string>
using namespace std;
int main()
{
string s = "this is a test, this is also a test, this is yet another test";
int strLen = 0;
strLen = s.length();
for() //this is where I can't seem to figure it out
cout << s << endl;
return 0;
}
AnsBekk
  • 59
  • 6
  • 1
    Here's the answer: `s[0] = std::toupper(s[0]);`. Replace `0` with the position of the letter you want to capitalize. – Thomas Matthews Sep 30 '20 at 22:43
  • 1
    Here you go: `for(auto& c : s) { c = c == 'i' ? (char)std::toupper(c) : c; }` – πάντα ῥεῖ Sep 30 '20 at 22:45
  • @ThomasMatthews Thank you. You solution works, but involves multiple entries. I appreciate it. – AnsBekk Sep 30 '20 at 22:51
  • @πάνταῥεῖ AWESOME! Thank you very much. – AnsBekk Sep 30 '20 at 22:52
  • 2
    It's not generally safe to call `std::toupper` on a `char` value from a `std::string` - you should use `std::toupper(static_cast(c))`. See [cppreference docs](https://en.cppreference.com/w/cpp/string/byte/toupper) - the argument is an `int` and must be representable as an `unsigned char`. Simply `char` - the element type in `std::string`, may be signed or unsigned depending on your implementation. (The reason for this is so implementations may simply index into an array of 256 `char`s - where the lowercase ones are replaced with uppercase ones, using the input as an index) – Tony Delroy Sep 30 '20 at 22:55

2 Answers2

1

Here is an std:: way:

#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
using namespace std;

int main()
{
  string s = "this is a test, this is also a test, this is yet another test";
  char ch = std::toupper('i');
  std::replace(s.begin(), s.end(), 'i', ch);
  cout << s << endl;
  return 0;
}
Vlad Feinstein
  • 10,960
  • 1
  • 12
  • 27
1
// Assume that all dependencies have been included
void replaceAllLetters (string& s, char toReplace) {
    char new = std::toupper(toReplace);
    std::replace(s.begin, s.end, toReplace, new);
}
void replaceOneLetter (string& s, int index) {
  if (index < s.size()) s[index] = std::toupper(s[index]);
}