2017年11月23日 星期四

[C_ST37-中] 字串比對(C++)

[C_ST37-中] 字串比對

問題描述:
輸入兩字串 A, B ,輸出 B 字串在 A 字串中第一次出現的位置, A 字串第一個字母的位置為 0 ,位置若 B 字串不為 A 的子字串,則輸出 -1 。
( 例: A 字串 : "ACDBAD" ,若 B 字串為 "DB" ,則輸出 2 ;若 B 字串為 "DA" ,則輸出 -1 。 )
輸入說明:
1. 鍵盤輸入二字串 A, B
2. 字串為 ASCII Code 組成,包含空白,且區分大小寫
輸出說明:
B 字串在 A 字串中的位置 ( 整數 ) ,若 B 不為 A 的子字串,則輸出 -1 。
範例:
Sample InputSample Output
 ACDBAD
DB
2
ACDBAD
DA
-1
This is a book.
book
10


  1. #include<iostream>  
  2. #include<iomanip>    
  3. #include<string>  
  4.   
  5. using namespace std;  
  6.   
  7. int main()  
  8. {  
  9.     // [C_ST37-中] 字串比對  
  10.     string strA, strB;  
  11.     cin.ignore();  
  12.     getline(cin, strA);  
  13.     getline(cin, strB);  
  14.     int found;  
  15.     found = strA.find(strB, 0);  
  16.     if(found != string::npos)  
  17.     {  
  18.         cout << found+1 << endl;  
  19.     }  
  20.     else  
  21.     {  
  22.         cout << -1 << endl;  
  23.     }  
  24. }  

沒有留言:

張貼留言