C - Prefix? Editorial by en_translator
If the length \(|S|\) of \(S\) is greater than the length \(|T|\) of \(T\),
then \(S\) cannot be a prefix of \(T\), so the answer is No.
Hereinafter we assume \(|S| \leq |T|\).
\(S\) is a prefix of \(T\) by checking if and only if \(S\) equals the first \(|S|\) characters of \(T\). Thus, in order to check if \(S = S_1S_2\ldots S_{|S|}\) is a prefix of \(T = T_1T_2\ldots T_{|T|}\), it is sufficient to check if \(S_i = T_i\) holds for all \(i = 1, 2, \ldots, |S|\).
In order to scan “all \(i\),” we can use a loop (like for statements) which is a standard feature in programming languages.
Note that the first character is indexed \(0\) instead of \(1\) depending on the language you use.
The following is a sample code in C++ for this problem.
#include <iostream>
using namespace std;
int main(void)
{
  string s, t;
  cin >> s >> t;
  
  if(s.size() > t.size()){
    cout << "No" << endl;
    return 0;
  }
  
  for(int i = 0; i < (int)s.size(); i++){
    if(s[i] != t[i]){
      cout << "No" << endl;
      return 0;
    }
  }
  cout << "Yes" << endl;
  
  return 0;
}
				posted:
				
				
				last update: