Page 272 - Computer Science Class 11 Without Functions
P. 272

Program 11.2 The number of common characters in a pair of strings

          01 '''
          02 Objective: To find the number of common characters in a pair of strings
          03 Inputs:
          04     str1 - string value
          05     str2 - string value
          06 Output: count of the number of common characters
          07 '''
          08
          09 str1 = input('Enter first string:')
          10 str2 = input('Enter second string:')
          11
          12 str1, str2 = str1.lower(), str2.lower()
          13
          14 distinctChar = []
          15 for char in str1 + str2:
          16     if char not in distinctChar:
          17         distinctChar.append(char)
          18
          19  print(f"The number of distinct characters between '{str1}' and '{str2}'
          20 is:", len(distinctChar))
        11.6.3 Searching for a Substring Within Another String

        Let us write a program that searches for a substring in a given string. To achieve this, we take two strings (string and
        substr) as inputs.
        ●  Since the two strings may comprise a mix of upper and lowercase characters, we first map them to the same case
           (line 13).
        ●  Next, we find the length (lengthSubstr) of the substring (line 14).
        ●  The for loop (lines 15-17) looks for a substring of length lengthSubstr that matches the given substr.

        ●  If substr is found, the program displays True (line 19) and False otherwise (line 21).

         Program 11.3 Searching for a substring in another string

          01 '''
          02 Objective: To search for a substring in given string
          03 Input:
          04     substr - string value
          05     string - string value
          06 Output: True - if substr is present in string, False, otherwise
          07 '''
          08
          09 substr = input('Enter the substring:')
          10 string = input('Enter the string in which the substring is to searched: ')
          11
          12 flag = False
          13 substr, string = substr.lower(), string.lower()
          14 lengthSubstr = len(substr)
          15 for index in range(len(string)):
          16     if substr == string[index:index+lengthSubstr]:
          17         flag = True
          18
          19 if flag == True:
          20     print('Yes, the ', substr, ' is present in the', string)
          21 else:
          22     print('No, the ', substr, ' is not present in the', string)


         270   Touchpad Computer Science-XI
   267   268   269   270   271   272   273   274   275   276   277