C++程序检查字符串是否已出现


假设我们有一个包含n个字符串的数组'stringArr'。我们逐个迭代字符串元素,找出数组中是否之前出现过该字符串。如果出现,则打印'已出现!',否则打印'未出现!'

问题类别

为了解决这个问题,我们需要操作字符串。编程语言中的字符串是由存储在特定数组类型数据中的字符流组成。一些语言将字符串指定为特定数据类型(例如Java、C++、Python);而其他一些语言则将字符串指定为字符数组(例如C)。字符串在编程中非常重要,因为它们通常是各种应用程序中首选的数据类型,并用作输入和输出的数据类型。有各种字符串操作,例如字符串搜索、子串生成、字符串剥离操作、字符串转换操作、字符串替换操作、字符串反转操作等等。查看下面的链接,了解如何在C/C++中使用字符串。

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

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

因此,如果我们问题的输入类似于n = 6,s = {"apple", "dog", "cat", "mouse", "apple", "cat"},则输出将为

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

步骤

为了解决这个问题,我们将遵循以下步骤:

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

示例

让我们看下面的实现来更好地理解:

#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;
}

输入

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

输出

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

更新于:2022年4月7日

浏览量:150

启动您的职业生涯

完成课程获得认证

开始
广告