• 0

How to compare 1 string against multiple strings?


Question

Ok, I am a beginner at c++ and I cannot figure out the best way to compare a string to multiple strings....

Basically I want something to do this:

1. User enters name such as John Doe, but I want it to not matter if they type it in uppercase, lowercase, etc.

2. Name is checked against multiple strings such as...(john doe) (John Doe) (JOHN DOE)

3. if the name the user enters matches one of those the result is 0, or something similar.

What is the best way to do this? Is there a way that I could just type one string to compare it to the name the user enters instead of every possibility? So I need a way to compare it disregarding the uppercase, lowercase....I think.

Thanks for any help!

Also, I can never think of any programs to make for practice, is there a website with some ideas?

17 answers to this question

Recommended Posts

  • 0
  PricklyPoo said:
Ok, I am a beginner at c++ and I cannot figure out the best way to compare a string to multiple strings....

Basically I want something to do this:

1. User enters name such as John Doe, but I want it to not matter if they type it in uppercase, lowercase, etc.

2. Name is checked against multiple strings such as...(john doe) (John Doe) (JOHN DOE)

3. if the name the user enters matches one of those the result is 0, or something similar.

What is the best way to do this? Is there a way that I could just type one string to compare it to the name the user enters instead of every possibility? So I need a way to compare it disregarding the uppercase, lowercase....I think.

Thanks for any help!

Also, I can never think of any programs to make for practice, is there a website with some ideas?

Take the string and change it to all upper or all lower then compare once.

  • 0
  PricklyPoo said:
But what happens if the user enters JoHn dOE....

You take the string "JoHn dOE" convert to all upper = "JOHN DOE" then comare. If all you want to do is verify that john doe was typed regardless of case then change the case of the string and compare to match. If you have to compare against a certain case (John Doe is different then john doe) then you need multiple compares.

  • 0

It doesn't matter. It changes the entire string to upper case. If you do that, like a8ball said, you can just compare 1 time instead of doing it multiple times.

  • 0
  a8ball said:
You take the string "JoHn dOE" convert to all upper = "JOHN DOE" then comare. If all you want to do is verify that john doe was typed regardless of case then change the case of the string and compare to match. If you have to compare against a certain case (John Doe is different then john doe) then you need multiple compares.
  IceBreakerG said:
It doesn't matter. It changes the entire string to upper case. If you do that, like a8ball said, you can just compare 1 time instead of doing it multiple times.

Oh, I see now, thanks!

  • 0

I just tried to make a quick program but I must be doing a lot wrong since I am getting errors, please help! :p

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

int main()
{

	char johndoe[] = "john doe";
	char name[50];

	cout << "Please Enter Your First And Last Name.\n" << endl;

	cin.getline(name, 50, '\n');

	name=tolower(name);

   if (strcmp(johndoe, name) = 0 ){

	cout << "You Are John Doe.\n";
	}
	else {
		 cout << "You Are Not John Doe.";
		 }
	return 0;
}

  • 0

Hi Prickly,

Some problems, tolower seems to expect one character, and it returns an int.

http://www.cplusplus.com/reference/clibrar...pe/tolower.html

So you need to loop through each character in your name (you know the number of times you have to loop by checking the length of your string), and convert them one by one.

  • 0

Thanks for the help!

I am just really having a hard time understanding this. :(

I tried to just use the code on that cplusplus website and replace it with my variables but it didn't work. :/

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

int main()
{
	int i=0;
	char johndoe[] = "john doe";
	char name[50];

	cout << "Please Enter Your First And Last Name.\n" << endl;

	cin.getline(name, 50, '\n');

	while (johndoe[i])
	{
		  name=johndoe[i];
		  putchar (tolower(name));
		  i++;
		  }


   if (strcmp(johndoe, name) = 0 ){

	cout << "You Are John Doe.\n";
	}
	else {
		 cout << "You Are Not John Doe.";
		 }
	return 0;
}

It just comes up with the char to int problem and incompatible types in assignment of `char' to `char[50] messages.

So I need to just do them one by one and keep looping? Isn't there a better way? What if I wanted to compare multiple strings, I would have to do a loop for each one then?

  • 0

You can also make it a bit more complex and make use of the <algorithm> header:

#include &lt;iostream&gt;
#include &lt;string&gt;
#include &lt;algorithm&gt;
#include &lt;cctype&gt;

int main ()
{
	std::string x = "John Doe";

	// transform(iterator start, iterator finish, iterator initialResultPosition, UnaryFunction op);
	// initialResultPosition - where to start storing the result for each iteration
	// (it is automatically incremented each iteration)
	// op - a pointer to a function
	std::transform(x.begin(), x.end(), x.begin(), toupper);
	std::cout &lt;&lt; x &lt;&lt; std::endl;
}

If you need more info, feel free to check out cplusplus.com's entry on the transform algorithm or cppreference.com's entry on the transform algorithm (or both). Note that cppreference keeps things simple. cplusplus.com prefers to give examples, and specify a LOT more on the page, which can make it difficult to figure out what you need to read.

Edit:

If you want to still do it without the algorithm, here it is:

for (int i = 0; i &lt; someString.length(); i++)
	someString[i] = toupper(someString[i]);

Edited by rpgfan
  • 0

Thanks rpg, I used the second code you posted and it works.

#include&lt;iostream&gt;
#include &lt;cctype&gt;
#include&lt;string&gt;
#include &lt;algorithm&gt;
using namespace std;

int main()
{

	string x = "john doe";
	string y;

	cout &lt;&lt; "Please Enter Your First And Last Name.\n" &lt;&lt; endl;

	getline(cin, y, '\n');

   for (int i = 0; i &lt; y.length(); i++)
	y[i] = tolower(y[i]);

   if (strcmp (x,y) == 0);
   {
			  cout &lt;&lt; "You Are John Doe.";

   cin.get();
}

The only problem is strcmp, it says I need two const chars, does that mean I have to save the results of the tolower function to chars somehow and then run strcmp?

  • 0

You shouldn't need to use strcmp. You can just use the '==' operator when you use C++ strings. :)

However, if you really needed to use strcmp, you would use strcmp(x.c_str(), y.c_str()). The c_str member function returns a C-string, a null-terminated array of chars.

  • 0
  rpgfan said:
You shouldn't need to use strcmp. You can just use the '==' operator when you use C++ strings. :)

However, if you really needed to use strcmp, you would use strcmp(x.c_str(), y.c_str()). The c_str member function returns a C-string, a null-terminated array of chars.

Hehe oh, ok.

Works perfectly now thanks!

#include&lt;iostream&gt;

using namespace std;

int main()
{

	string x = "john doe";
	string y;

	cout &lt;&lt; "Please Enter Your First And Last Name.\n" &lt;&lt; endl;

	getline(cin, y, '\n');

   for (int i = 0; i &lt; y.length(); i++)
	y[i] = tolower(y[i]);

   if ( x == y )
   {
			  cout &lt;&lt; "You Are John Doe.";
			  }
   else 
   {
		cout &lt;&lt; "You Are Not John Doe.";
		}

   cin.get();
}

Here it is if anyone other beginner ever needs it as a reference. :p

  • 0

Oh, and I should note that the loop should actually use an unsigned integer, not a signed integer, which is the default if no signed/unsigned specifier is...specified.

The reason for this is because the length member function returns a size. Obviously, you can have a zero-length (empty) string, but you can't go any lower than 0, which is why it should be unsigned. In fact, gcc complains about comparing a signed value (the loop variable) with an unsigned value (x.length()).

Happy coding! :)

  • 0

Quickly threw this together. Untested - but should work.

#include &lt;iostream&gt;
#include &lt;string&gt;

int main()
{
	std::string name;
	std::string nameCompare = "John Doe";

	std::cout &lt;&lt; "Enter name: ";
	getline(std::cin, name);

	if (name.compare(nameCompare) == 0)
	{
		std::cout &lt;&lt; "identical" &lt;&lt; std::endl;
	}
	else
	{
		std::cout &lt;&lt; "not identical" &lt;&lt; std::endl;
	}
}

EDIT: Nevermind, didn't see that you wanted to check for varying cases.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • I did not spot that! "This article was generated with some help from AI and reviewed by an editor", to me, suggests it was indeed entirely generated by AI and just looked over by Sayan. Bond. Mate 😔
    • Good. They shouldn't be allowed to block this stuff anyway. They're getting paid to host your app to begin with, they get a cut of the sale of the app to start. After the app leaves their servers and is on your device, the dev should be free to offer you alternative options for payments or links to their site directly from within their own app. Since these systems don't use any of Apples services at all, there should also be zero reason they should demand a cut for doing nothing like they're some digital mafia.
    • I suspect this was primarily developed with the Switch 2 in mind, which would explain the poor visuals. It seems like they're hoping the nostalgic GoldenEye 64 crowd is still loyal to Nintendo consoles. Unfortunately, this might be yet another title limited by development for underpowered Nintendo hardware.
    • Amazon's Lab126 ventures into "Physical AI" with new robotics team by Paul Hill Amazon has announced that it’s forming a new agentic AI team within its secretive hard research and development division, Lab126, to begin work on physical AI. Specifically, the company is looking to develop an agentic AI framework for use in robotics, which could start to impact blue-collar jobs, especially at its warehouses. Agentic AI is one of the latest developments in AI, superseding the previous generative AI that took off with the launch of ChatGPT. Agentic AI models are special because they can complete multi-step actions for the user to complete complex tasks. Thanks to all the visual and audio capabilities added to generative AI in previous years, these agentic models can perceive their environment, reason, plan, and act to achieve goals with minimal human intervention. If Amazon can successfully bring agentic AI to robots, they will finally be able to interact with the real world in a way they can’t today, as software running on a computer. Many people are concerned about AI’s impact on white-collar jobs right now, but when Amazon develops physical AI, it will also affect blue-collar manual work. The work is going to be carried out by Amazon’s R&D company, Lab126. It was set up over 20 years ago and has created many iconic Amazon devices, including the Kindle, Fire tablets, Amazon Fire TV, Amazon Echo devices, and more. Who it affects, and how The biggest impact of physical AI developed by Lab126 will be on Amazon’s warehouses and logistics. The company said it wants to create robots that can perform tasks based on natural language instructions. As usual for a big tech company, Amazon claims that these robots will be assistants, but it’s difficult to see how they won’t reduce the need for people. Solely based on Amazon’s plans to automate work in its factories, customers will see an indirect impact from the move through faster deliveries and potentially lower costs. The decision by Amazon to focus on agentic AI in robots is pretty interesting because so far, we’ve mainly been hearing about agentic AI limited to computer applications, such as intelligent web browsers like Opera Neon. Why it's happening Amazon has a reputation for being an efficient company, particularly when it comes to the employment of warehouse workers who are known to have strict restroom breaks. Creating robots that can help speed up warehouse activities will further boost efficiency at the company and could potentially reduce its costs and improve safety. The beginning of work on physical AI is just the next evolution of AI that we could start to hear about in the coming months and years. As agentic AI gets better, companies will be looking to see what they can advance next and physical AI may be where they choose to go next; it certainly seems like this is what Amazon has settled on in this move. If Amazon’s physical AI doesn’t lead to mass layoffs of warehouse employees, it could drastically boost worker safety. Employees could potentially be less fatigued from moving around so much, which could lead to better concentration and fewer accidents. Right now, Amazon claims that these robots will only be assistants and not replacements. While Amazon will certainly be a leader in physical AI, given its massive wealth to throw at the problem, once the technology is available, it will likely be available for sale to other businesses to use, too. Caveats and what to watch for While it’s a notable development, it still sounds like Amazon is in the early stages of developing these physical AI systems, given that it has only just set up the team. We also don’t know what specific products Amazon is planning to build or the timelines for deployment. Ever since generative AI came onto the scene, there has been discussion of AI safety. With AI moving into the physical world, it will also bring up discussion about the safety concerns. Current measures are mainly concerned with AI software running on computers, not when it interacts physically with the world. Finally, and probably the biggest concern, what will these “assistants” do to people’s jobs? Companies will likely find themselves bringing in fewer new hires initially, but it could also displace people from their jobs. Source: CNBC
    • Nintendo Switch 2 launches, where to buy and a list of games that it may not support by Sayan Sen Nintendo announced the Switch 2 back in early April this year and then followed that up with more details related to performance and hardware features later. The company touted 10x the performance of the Switch. However, on the flip side, the battery suffers, and you also need new microSD Express cards for storage. For those who need a refresher, here are the technical specification details of the Switch 2: Specification Details Dimensions Approx. 166mm x 272mm x 13.9mm (with Joy-Con 2 attached); Maximum thickness from control stick tip to ZL/ZR buttons: 30.7mm Weight Approx. 401g (console only); Approx. 534g (with Joy-Con 2 controllers attached) Screen 7.9-inch capacitive touch LCD; 1920x1080 resolution; HDR10 support; VRR up to 120 Hz CPU/GPU Custom processor made by NVIDIA Storage 256 GB UFS (a portion reserved for system use) Communication Wireless LAN (Wi‑Fi 6), Bluetooth; Wired LAN available in TV mode via dock Video Output Up to 3840x2160 at 60 fps via HDMI in TV mode; Supports 120 fps at lower resolutions; HDR10 enabled Audio Output Linear PCM 5.1 channel via HDMI; Stereo speakers Microphone Built-in monaural microphone with noise cancellation, echo cancellation and auto gain control Buttons POWER and Volume buttons USB Ports 2 USB Type-C ports (bottom port for charging/dock connection; top port for accessories/charging) Audio Jack 3.5mm stereo mini plug (CTIA standard) Game Card Slot Supports both Nintendo Switch 2 and Nintendo Switch game cards Expansion Slot microSD Express card slot (compatible with cards up to 2 TB; other microSD cards can copy screenshots and videos) Sensors Accelerometer, gyroscope, brightness sensor Battery Lithium-ion, 5220 mAh; Approx. 2–6.5 hours lifetime; 3-hour charge time in sleep mode Dock Approx. 115mm x 201mm x 51.2mm; Weight: approx. 383g For those looking to get one, major retailers like Walmart, GameStop, Best Buy, and Target have all confirmed that they will have limited console stock from time to time so you will need to be on alert and check back. Nintendo has also published a full list of games that may not work on the Switch 2: Borderlands 3 Chrono Cross: The Radical Dreamers Edition Crash Bandicoot N-Sane Trilogy Guilty Gear XX Accent Core Plus R KarmaZoo Marvel vs. Capcom Fighting Collection: Arcade Classics Mortal Kombat 1 Overwatch 2 Star Wars: Knights of the Old Republic II: The Sith Lords Star Wars Republic Commando Super Mega Baseball 4 Tombi! Special Edition Tony Hawk's Pro Skater 1+2 Touhou Genso Wanderer Reloaded Ty the Tasmanian Tiger HD Warriors: Abyss However, keep in mind that Nintendo last updated the support list last month on May 27th and the company may still be testing these. So keep an eye on the official list of games on this webpage here on Nintendo's site. Have you managed to pick up the Nintendo Switch 2? Let us know in the comments.
  • Recent Achievements

    • Rookie
      GTRoberts went up a rank
      Rookie
    • First Post
      James courage Tabla earned a badge
      First Post
    • Reacting Well
      James courage Tabla earned a badge
      Reacting Well
    • Apprentice
      DarkShrunken went up a rank
      Apprentice
    • Dedicated
      CHUNWEI earned a badge
      Dedicated
  • Popular Contributors

    1. 1
      +primortal
      397
    2. 2
      +FloatingFatMan
      177
    3. 3
      snowy owl
      170
    4. 4
      ATLien_0
      167
    5. 5
      Xenon
      134
  • Tell a friend

    Love Neowin? Tell a friend!