Open In App

String generated by typing given string in a keyboard having the button of given character faulty

Improve
Improve
Like Article
Like
Save
Share
Report

Given a string str and a character ch, where the button of character ch is not working correctly. After pressing that key, it toggles the Caps Lock instead of that letter. The task is to print the string generated after typing str on such a faulty keyboard. 
Note: The string may contain both upper and lower case characters.

Examples:

Input: str = “This keyboard is faulty.”, ch = ‘a’
Output: This keyboard IS Faulty.
Explanation: 
‘a’ is encountered at position 10 (0 based indexing), which turns Caps Lock ON, resulting in capitalizing the further characters till next ‘a’ is encountered at position 18, which turns it OFF.
Therefore the resultant string is “This keyboard IS Faulty.”.

Input: str = “Read the phrase.”, ch = ‘z’
Output: Read the phrase.
Explanation: Since ‘z’ does not occur in the string, the string str is printed correctly.

Approach: Follow the steps below to solve the above problem:

  • Initialize a boolean variable CapsLockOn as false that will stores whether the Caps Lock is on or not.
  • Traverse the given string character by character and perform the following:
    • If any character in the string is the same as ch, then delete the current character and reverse the value of CapsLockOn and continues to iterate the string.
    • If CapsLockOn is True, then update the current character to uppercase or vice-versa.
    • If CapsLockOn is False, then leave the current character unchanged.
  • After complete traversal of the string, print the resultant string.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the updated string
// after typing on faulty keyboard
string faultyKeyboard(string str, char ch)
{
    // Stores the status of Caps Lock
    bool CapsLockOn = false;
 
    int i = 0;
 
    // Traverse over the string
    while (i < str.length()) {
 
        // If ch is lower case
        if (str[i] == ch
            || str[i] == char(ch + 32)) {
 
            // Toggle the caps lock
            CapsLockOn = !CapsLockOn;
 
            // Delete i-th character
            str.erase(i, 1);
 
            continue;
        }
 
        // If ch is upper case
        else if (str[i] == ch
                 || str[i] == char(ch + 32)) {
 
            // Toggle the caps lock
            CapsLockOn = !CapsLockOn;
 
            // Delete i-th character
            str.erase(i, 1);
 
            continue;
        }
 
        // If CapsLockOn is true
        else if (CapsLockOn) {
 
            if (islower(str[i])) {
 
                // Convert the lower case
                // character to upper case
                str[i] = toupper(str[i]);
            }
            else {
 
                // Convert the upper case
                // character to lower case
                str[i] = tolower(str[i]);
            }
        }
 
        // Increment for next iteration
        i++;
    }
 
    // Return the resultant string
    return str;
}
 
// Driver Code
int main()
{
    // Given string str
    string str = "This keyboard is faulty.";
 
    char ch = 'a';
 
    // Function Call
    cout << faultyKeyboard(str, ch);
 
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
 
class GFG{
   
// Function to return the updated string
// after typing on faulty keyboard
static String faultyKeyboard(String str, char ch)
{
     
    // Stores the status of Caps Lock
    boolean CapsLockOn = false;
 
    int i = 0;
 
    // Traverse over the string
    while (i < str.length())
    {
         
        // If ch is lower case
        if (str.charAt(i) == ch ||
            str.charAt(i) == (char)((int)ch + 32))
        {
             
            // Toggle the caps lock
            CapsLockOn = !CapsLockOn;
 
            // Delete i-th character
            str = str.substring(0, i) +
                  str.substring(i + 1);
                   
           // str.replace(str.charAt(i),'');
 
            continue;
        }
 
        // If ch is upper case
        else if (str.charAt(i) == ch ||
                 str.charAt(i) == (char)((int)ch + 32))
        {
             
            // Toggle the caps lock
            CapsLockOn = !CapsLockOn;
 
            // Delete i-th character
           str = str.substring(0, i) +
                 str.substring(i + 1); 
           // str.replace(str.charAt(i),'');
 
            continue;
        }
 
        // If CapsLockOn is true
        else if (CapsLockOn)
        {
            if (str.charAt(i) >='a' &&
                str.charAt(i) <= 'z')
            {
                 
                // Convert the lower case
                // character to upper case
                char c = Character.toUpperCase(
                         str.charAt(i));
                str = str.substring(0, i) + c +
                      str.substring(i + 1);
                       
                // str = str.replace(str.charAt(i),
                // Character.toUpperCase(str.charAt(i)));
            }
            else
            {
                 
                // Convert the upper case
                // character to lower case
                char c = Character.toLowerCase(
                         str.charAt(i));
                str = str.substring(0, i) + c +
                      str.substring(i + 1);
                       
               // str = str.replace(str.charAt(i),
               // Character.toLowerCase(str.charAt(i)));
            }
        }
 
        // Increment for next iteration
        i++;
    }
 
    // Return the resultant string
    return str;
}
 
// Driver Code
public static void main(String args[])
{
     
    // Given string str
    String str = "This keyboard is faulty.";
 
    char ch = 'a';
 
    // Function Call
    System.out.print(faultyKeyboard(str, ch));
}
}
 
// This code is contributed by ipg2016107


Python3




# Python 3 program for the above approach
 
# Function to return the updated string
# after typing on faulty keyboard
def faultyKeyboard(str, ch):
   
    # Stores the status of Caps Lock
    CapsLockOn = False
    i = 0
 
    # Traverse over the string
    while (i < len(str)):
       
        # If ch is lower case
        if (str[i] == ch or str[i] == chr(ord(ch) + 32)):
           
            # Toggle the caps lock
            if(CapsLockOn == False):
                CapsLockOn = True
            else:
                CapsLockOn = False
                 
            # Delete i-th character
            str = str.replace(str[i],'', 1)
 
            continue
 
        # If ch is upper case
        elif(str[i] == ch or str[i] == chr(ord(ch) + 32)):
           
            # Toggle the caps lock
            if(CapsLockOn==False):
                CapsLockOn = True
            else:
                CapsLockOn = False
                 
            # Delete i-th character
            str = str.replace(str[i],'', 1)
            continue
 
        # If CapsLockOn is true
        elif (CapsLockOn):
            if (ord(str[i]) >= 97 and ord(str[i]) <= 122):
               
                # Convert the lower case
                # character to upper case
                #indexes = set((i))
                chars = list(str)
                chars[i] = chars[i].upper()
 
                str = ''.join(chars)
            else:
               
                #indexes = set((i))
                chars = list(str)
                chars[i] = chars[i].lower()
 
                str = ''.join(chars)
                 
        # Increment for next iteration
        i += 1
 
    # Return the resultant string
    return str
 
# Driver Code
if __name__ == '__main__':
   
    # Given string str
    str = "This keyboard is faulty."
    ch = 'a'
 
    # Function Call
    print(faultyKeyboard(str, ch))
 
# This code is contributed by SURENDRA_GANGWAR.


C#




// C# program for the
// above approach
using System;
class GFG{
 
// Function to return the updated
// string after typing on faulty
// keyboard
static string faultyKeyboard(string str,
                             char ch)
{
 
  // Stores the status of
  // Caps Lock
  bool CapsLockOn = false;
 
  int i = 0;
  // Traverse over the string
  while (i < str.Length)
  {
    // If ch is lower case
    if (str[i] == ch ||
        str[i] == (char)(ch + 32))
    {
      // Toggle the caps lock
      CapsLockOn = !CapsLockOn;
 
      // Delete i-th character
      str = str.Substring(0, i) +
            str.Substring(i + 1);
       
      continue;
    }
 
    // If ch is upper case
    else if (str[i] == ch ||
             str[i] == (char)(ch + 32))
    {
      // Toggle the caps lock
      CapsLockOn = !CapsLockOn;
 
      // Delete i-th character
      str = str.Substring(0, i) +
            str.Substring(i + 1);
 
      continue;
    }
 
    // If CapsLockOn is true
    else if (CapsLockOn)
    {
      if (str[i] >= 'a' &&
          str[i] <= 'z')
      {
        // Convert the lower case
        // character to upper case
        char c = (char)(str[i] - 32);
        str = str.Substring(0, i) + c +
              str.Substring(i + 1);
      }
      else if (str[i] >= 'A' &&
               str[i] <= 'Z')
      {
        // Convert the upper case
        // character to lower case
        char c = (char)(str[i] + 32);
        str = str.Substring(0, i) + c +
              str.Substring(i + 1);
      }
    }
 
    // Increment for next
    // iteration
    i++;
  }
 
  // Return the resultant
  // string
  return str;
}
 
// Driver Code
public static void Main()
{
  // Given string str
  string str = "This keyboard is faulty.";
 
  char ch = 'a';
 
  // Function Call
  Console.Write(faultyKeyboard(str, ch));
}
}
 
// This code is contributed by Chitranayal


Javascript




<script>
// Javascript program for the above approach
 
// Function to return the updated string
// after typing on faulty keyboard
function faultyKeyboard(str,ch)
{
 
    // Stores the status of Caps Lock
    let CapsLockOn = false;
    let i = 0;
  
    // Traverse over the string
    while (i < str.length)
    {
          
        // If ch is lower case
        if (str[i] == ch ||
            str[i] == String.fromCharCode(ch.charCodeAt(0) + 32))
        {
              
            // Toggle the caps lock
            CapsLockOn = !CapsLockOn;
  
            // Delete i-th character
            str = str.substring(0, i) +
                  str.substring(i + 1);
                    
           // str.replace(str.charAt(i),'');
  
            continue;
        }
  
        // If ch is upper case
        else if (str[i] == ch ||
                 str[i] == String.fromCharCode(ch.charCodeAt(0) + 32))
        {
              
            // Toggle the caps lock
            CapsLockOn = !CapsLockOn;
  
            // Delete i-th character
           str = str.substring(0, i) +
                 str.substring(i + 1);
           // str.replace(str.charAt(i),'');
  
            continue;
        }
  
        // If CapsLockOn is true
        else if (CapsLockOn)
        {
            if (str[i] >='a' &&
                str[i] <= 'z')
            {
                  
                // Convert the lower case
                // character to upper case
                let c = str[i].toUpperCase();
                str = str.substring(0, i) + c +
                      str.substring(i + 1);
                        
                // str = str.replace(str.charAt(i),
                // Character.toUpperCase(str.charAt(i)));
            }
            else
            {
                  
                // Convert the upper case
                // character to lower case
                let c = str[i].toLowerCase();
                str = str.substring(0, i) + c +
                      str.substring(i + 1);
                        
               // str = str.replace(str.charAt(i),
               // Character.toLowerCase(str.charAt(i)));
            }
        }
  
        // Increment for next iteration
        i++;
    }
  
    // Return the resultant string
    return str;
}
 
// Driver Code
 
// Given string str
let str = "This keyboard is faulty.";
let ch = 'a';
 
// Function Call
document.write(faultyKeyboard(str, ch));
 
// This code is contributed by rag2127
</script>


Output

This keyboRD IS Fulty.

Time Complexity: O(N)
Auxiliary Space: O(1)



Last Updated : 22 Nov, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads