Theme
Primary Color
Lesson 24

String Starts With

محتوى الدرس

#include <iostream>
#include <vector>
using namespace std;

/*
  String Starts With
  "Elzero Web School" -> "Elzero" -> True
  "Hell" -> "Hello" -> False -> Prefix > Main String
*/

bool startsWith(string st, string prefix, bool caseSensitive = true)
{
  if (st.length() < prefix.length())
    return false;

  for (int i = 0; i < prefix.length(); i++)
  {
    if (caseSensitive)
    {
      if (st[i] != prefix[i])
      {
        return false;
      }
    }
    else // Case Not Sensitive
    {
      if (st[i] >= 'A' && st[i] <= 'Z')
      {
        st[i] += 32;
      }
      if (prefix[i] >= 'A' && prefix[i] <= 'Z')
      {
        prefix[i] += 32;
      }
      if (st[i] != prefix[i])
      {
        return false;
      }
    }
  }

  return true;
}

int main()
{
  cout << boolalpha;
  cout << startsWith("Hell", "Hello") << endl;                      // False
  cout << startsWith("Hello", "Hello") << endl;                     // True
  cout << startsWith("Elzero Web School", "Elzero") << endl;        // True
  cout << startsWith("Elzero Web School", "elzero", false) << endl; // True
  return 0;
}