51Nod-2148 字元出現位置【水題】
阿新 • • 發佈:2018-12-10
請你幫小瓜找一找某個字元在字串中第一次出現的位置是多少。
Input
第一行一個整數n(1 <=n <= 10000),表示字串的長度。 第二行一個長度為n的字串,保證每個字元都是小寫字母。 第三行一個字元,表示需要尋找的字元。
Output
一行一個整數,表示字元在字串中第一次出現的位置(從第0位開始記)。如果字元沒有出現過,則輸出-1。
Input示例
5 abcde d
Output示例
3
問題分析:
這是一個簡單題,在字串中找字元。給出C語言和C++語言的2種程式,不解釋。
程式說明:(無)
題記:(略)
參考連結:(無)
AC的C語言程式如下:
#include <stdio.h> #define N 10000 char s[N + 1], t[2]; int main(void) { int n, ans, i; scanf("%d", &n); scanf("%s", s); scanf("%s", t); ans = -1; for(i = 0; i < n; i++) if(s[i] == t[0]) { ans = i; break; } printf("%d\n", ans); return 0; }
AC的C++語言程式如下:
#include <iostream>
using namespace std;
int main()
{
int n;
string a, b;
cin >> n >> a >> b;
std::size_t ans = a.find(b);
cout << ((ans == std::string::npos) ? -1 : (int)ans) << endl;
return 0;
}