C++ Program to check if a string has been seen before

C++Server Side ProgrammingProgramming

Suppose, we have n number of strings given to us in an array 'stringArr'. We iterate through the string elements one by one and find out if a string has appeared before in the array. If such occurs, we print 'Seen Before!' or otherwise, we print 'Didn't see before!'

Problem Category

To solve this problem, we need to manipulate strings. Strings in a programming language are a stream of characters that are stored in a particular array-like data type. Several languages specify strings as a specific data type (eg. Java, C++, Python); and several other languages specify strings as a character array (eg. C). Strings are instrumental in programming as they often are the preferred data type in various applications and are used as the data type for input and output. There are various string operations, such as string searching, substring generation, string stripping operations, string translation operations, string replacement operations, string reverse operations, and much more. Check out the links below to understand how strings can be used in C/C++.

https://www.tutorialspoint.com/cplusplus/cpp_strings.htm

https://www.tutorialspoint.com/cprogramming/c_strings.htm

So, if the input of our problem is like n = 6, s = {"apple", "dog", "cat", "mouse", "apple", "cat"}, then the output will be

Didn't see before!
Didn't see before!
Didn't see before!
Didn't see before!
Seen Before.
Seen Before.

Steps

To solve this, we will follow these steps −

Define one set s
for initialize i := 0, when i < n, update (increase i by 1), do:
   if stringArr[i] is present in s, then:
      print("Seen Before.")
   Otherwise
      print("Didn't see before!")
      insert stringArr[i] into s

Example

Let us see the following implementation to get better understanding −

#include<bits/stdc++.h>
using namespace std;
void solve(int n, string stringArr[]) {
   set<string> s;
   for(int i = 0; i < n; i++) {
      if(s.count(stringArr[i]))
         cout << "Seen Before." << endl;
      else{
         cout<< "Didn't see before!" <<endl;
         s.insert(stringArr[i]);
      }
   }
}
int main() {
   int n = 6;
   string s[] = {"apple", "dog", "cat", "mouse", "apple", "cat"};
   solve(n, s);
   return 0;
}

Input

6, {"apple", "dog", "cat", "mouse", "apple", "cat"}

Output

Didn't see before!
Didn't see before!
Didn't see before!
Didn't see before!
Seen Before.
Seen Before.
raja
Updated on 07-Apr-2022 08:50:15

Advertisements