• 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

    • OontZ Angle 3 Coca-Cola Edition Bluetooth Speaker: Worth it at 25% off? by Paul Hill If you are looking for a portable Bluetooth speaker for yourself or for Father’s Day, check out this OontZ Coca-Cola branded Angle 3 Bluetooth speaker. Right now, you can pick it up for just $30, thanks to a recent 25% discount from the previous $40 price tag. Aside from the Coca-Cola branding, this speaker has a range of nifty features including a 100-foot range, a 14-hour battery, IPX5 water resistance, it promises no distortion of sound, and its shape ensures it won’t fall over. What it does (and doesn’t) The Oontz Bluetooth Speaker Angle 3 Coca-Cola Edition is super portable, making it an ideal choice for when you’re traveling. The speaker is just 5.3 inches long and weighs just 10 ounces. The width and height of the speaker are both under three inches and its triangular shape ensures it won’t fall over so you can put it down quickly whenever you’re out and about. According to OontZ, the speaker has 10 watts output that is “surprisingly loud” with “zero distortion” even when you turn it up to the max. These OontZ speakers are crafted by Cambridge Soundworks, a firm that has received critical acclaim since its inception in 1988. The firm is praised for delivering solid sound quality and construction - it makes some of the industry’s best speakers and offers excellent value for the price. As a travel speaker, it’ll probably end up on the beach or next to swimming pools where it can get wet. You don’t need to worry about splashing it though because it comes with IPX5 water resistance meaning it’s splash-proof, suitable for the shower, beaches, or the pool. While it will offer protection against splashes, it shouldn’t be submerged under water. On a single charge, the speaker will last for 14 hours on a single charge and connects to your device using Bluetooth 5.0. It has a good range of 100 feet so it shouldn’t become choppy just because you went into the next room with your phone. Should you buy? This OontZ Coca-Cola Bluetooth speaker is ideal for anyone who wants a great listening experience at home or on the go. It’s also a good choice for anyone looking for good sound on a budget as it’s now $30, which won’t break the bank. The main strengths of the speaker are its excellent value at the discounted price, reliable connectivity, and the good battery life considering its size. The fact that it’s from a reputable brand, Cambridge Soundworks, is also key. The iconic Coca-Cola branding may not be for everybody but it will definitely stand out with that vibrant red color. The IPX5 is also good to protect against splashes but it’s not fully waterproof, so if you need that, this speaker might not be for you. Oontz Bluetooth Speaker Angle 3 Coca-Cola Edition: $29.99 (Amazon US) - MSRP $39.99 / 25% off This Amazon deal is US-specific and not available in other regions unless specified. If you don't like it or want to look at more options, check out the Amazon US deals page here. Get Prime (SNAP), Prime Video, Audible Plus or Kindle / Music Unlimited. Free for 30 days. As an Amazon Associate, we earn from qualifying purchases.
    • GPUs selling higher than their MSRP is the new norm it seems. This shouldn't surprise anyone. Dumb duopoly, if Intel could just stop shooting itself in the foot and release some more cards and undercut the other two that'd be great.
    • I saw that recently, and the thing that would be useful also would be to have the PC model in that spec card as well. I know that it's on the main portal page of System, but repeating it in this "Device specs" module, especially if it's meant for the main specs of the computer, would certainly be useful.
    • Do you want a little in the ground or a lot in the air?
    • Bethesda readying two updates for Oblivion Remastered targeting bugs and performance by Pulasthi Ariyasinghe The surprise release of The Elder Scrolls IV: Oblivion Remastered was a massive success for Bethesda and Microsoft, with the title going on to gain over four million players in just three days at launch while also breaking franchise records for concurrent players. While reactions to the game have been positive from both critics and players, plenty of complaints have since been pouring in about the state of the remaster. Now, Bethesda is aiming to push out updates to resolve these concerns. Today, the company revealed that two updates are currently planned for the RPG, both with different scopes. The first of these is already available in beta form to Steam players. It seems Bethesda is using the same beta update format it uses for Starfield for this Elder Scrolls entry as well. "Thanks for all your excitement and feedback since the launch of The Elder Scrolls IV: Oblivion Remastered," said the development team today. "We are actively working on two separate updates to be launched in the coming weeks, both of which will come to our Steam Beta first, before being released to all other platforms." According to the studio, the first update is focused on "quests, major bugs and blockers, and quality of life fixes. " Following the June 5 launch on the Steam beta platform, all other PC players, as well as those on Xbox Series X|S, PlayStation 5, and Game Pass subscribers, will receive the update on June 11. The beta changelog for Update 1.1 can be seen here, with bug fixes coming for the UI, gameplay, quests, and more. Multiple crashes have been resolved here, with many being related to loading saves and exploring specific locations. Instances of infinite loading, alt-tab freezing, resetting settings, and more are being targeted with fixes, too. To opt into the Elder Scrolls IV: Oblivion Remastered beta update, Steam players can head into the game's properties, select Betas, and choose the [beta] branch to receive the new build. While Bethesda hasn't revealed any release dates for the second update, it did say that improving performance will be its main focus. This is a major point of criticism for the title at the moment, so the update can't come soon enough.
  • Recent Achievements

    • Week One Done
      jbatch earned a badge
      Week One Done
    • First Post
      Yianis earned a badge
      First Post
    • 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
  • Popular Contributors

    1. 1
      +primortal
      408
    2. 2
      +FloatingFatMan
      181
    3. 3
      snowy owl
      178
    4. 4
      ATLien_0
      172
    5. 5
      Xenon
      135
  • Tell a friend

    Love Neowin? Tell a friend!