9626. startsWith endsWith

 

Three lines of characters is given. Check if the second line is a prefix of the first line. Check if the third line is a suffix of the first line.

 

Input. Three lines, each contains no more than 100 characters.

 

Output. In the first line print true or false depending on whether second line is a prefix of the first one. In the second line print true or false depending on whether third line is a suffix of the first one.

 

Sample input

Sample output

qwerty

qwe

ty

true

true

 

 

SOLUTION

strings

 

Algorithm analysis

Function

char *strstr(const char *haystack, const char *needle)

finds the first occurrence of the substring needle in the string haystack

String b is a prefix of a if b appears in a starting at position 0.

String c is a suffix of a if c appears in a starting at position

a + strlen(a) – strlen(c)

 

Algorithm realization

Declare three char arrays.

 

char a[101], b[101], c[101];

 

Read three input strings.

 

gets(a);

gets(b);

gets(c);

 

String b is a prefix of a if b appears in a starting at position 0.

 

if (strstr(a, b) == a)

  puts("true");

else

  puts("false");

 

String c is a suffix of a if c appears in a starting at position a + strlen(a) – strlen(c).

 

if (strstr(a + strlen(a) - strlen(c), c) == a + strlen(a) - strlen(c))

  puts("true");

else

  puts("false");

 

Algorithm realization – Ñ++

 

#include <iostream>

#include <string>

using namespace std;

 

string a, b, c;

int len;

 

int main()

{

  cin >> a >> b >> c;

  if (a.substr(0, b.size()) == b)

    puts("true");

  else

    puts("false");

 

  if (a.substr(a.size() - c.size(), c.size()) == c)

    puts("true");

  else

    puts("false");

 

  return 0;

}

 

Java realization

 

import java.util.*;

 

public class Main

{

  public static void main(String[] args)

  {

    Scanner con = new Scanner(System.in);

    String s = con.nextLine();

    if (s.startsWith(con.nextLine()))

      System.out.println("true"); else System.out.println("false");

    if (s.endsWith(con.nextLine()))

        System.out.println("true"); else System.out.println("false");   

    con.close();

  }

}

 

Python realization

 

s = input()

start = input()

end = input()

 

if s.startswith(start):

  print("true")

else:

  print("false")

 

if s.endswith(end):

  print("true")

else:

  print("false")