Capitalize given part of string?

Hi everyone!

I have a program, where I receive a text from the user. In this string, there are parts between quotation marks, as well. My task is to capitalize the part that aren't between the quotation marks, for example:

Input: The "yellow" flower.
Output: THE "yellow" FLOWER.

I was considering the idea of finding the quotation marks of the string and until a quotation mark, I would add (+=) the part of the string, by letters to a result string using toupper() and the part between the quotation marks just simply adding to the string with +=.

What do you think? If you have any suggestions, I'm all ears!!
(1) Do it as a function
(2) Pass the string by value as an argument and operate on this copy within the function.
(3) Keep a boolean variable (say, inQuotes) to determine whether you are currently within quotes. Initialise it to false and toggle it every time you pass a ". (I guess that makes it a state machine.)
(4) Go through the string character by character and when inQuotes is currently false change any alphabetic character to upper case.
(5) Return the amended string.

I would change an existing string rather than use +=, to avoid continual memory reallocation, especially unnecessary when adding unchanged characters, but that's your choice.
Last edited on
There are various ways of doing this. The simplest is probably based upon lastchance's method. But the question implies changing the original string? Is this what is wanted - or do you want a new string with the text changed?

As C++20 changing the original string (but its easy to change it into creating a new changed string):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <string>
#include <cctype>

int main()
{
	std::string str {R"(The "yellow" flower.)"};

	for (bool qte {}; auto& ch : str)
		if (qte = ch == '\"' ? !qte : qte; !qte)
			ch = static_cast<char>(std::toupper(static_cast<unsigned char>(ch)));

	std::cout << str << '\n';
}



THE "yellow" FLOWER.

Last edited on
Thanks everyone a ton for the answers, it worked perfectly!! :D
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>
#include <cctype>
using namespace std;

string filter ( string s )
{
   bool inQuotes = false;
   for ( char &c : s )
   {
      if ( c == '\"' ) inQuotes = !inQuotes;
      if ( !inQuotes && isalpha( c ) ) c = toupper( c );
   }
   return s;
}

int main()
{
   cout << filter( R"(The "yellow" flower.)" ) << '\n';     // Raw string
   cout << filter( "The \"yellow\" flower."  ) << '\n';     // Without raw string
}


THE "yellow" FLOWER.
THE "yellow" FLOWER.
Topic archived. No new replies allowed.