C++程式檢查字串是否已出現


假設我們有一個包含n個字串的陣列'stringArr'。我們逐個迭代字串元素,找出陣列中是否之前出現過該字串。如果出現,則列印'已出現!',否則列印'未出現!'

問題類別

為了解決這個問題,我們需要操作字串。程式語言中的字串是由儲存在特定陣列型別資料中的字元流組成。一些語言將字串指定為特定資料型別(例如Java、C++、Python);而其他一些語言則將字串指定為字元陣列(例如C)。字串在程式設計中非常重要,因為它們通常是各種應用程式中首選的資料型別,並用作輸入和輸出的資料型別。有各種字串操作,例如字串搜尋、子串生成、字串剝離操作、字串轉換操作、字串替換操作、字串反轉操作等等。檢視下面的連結,瞭解如何在C/C++中使用字串。

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

https://tutorialspoint.tw/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

啟動您的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.