TeachingBee

The 10 Most Common C Interview Questions On Strings

C interview Questions On Strings

Introduction

C is among the most well-known computer languages, beacuse of its structure and the high level abstraction feature, its machine-independent function and so on. C language was created for the UNIX operating system and as such it is closely linked to UNIX which is among the most well-known network operating systems used in the present and is the core of the internet’s superhighway data.

The String of C is nothing more than the collection of characters.  C always considers strings as a single data even though it is surrounded by whitespaces. One character can be described using a single quote representation. Strings are represented with the double quotes.

For this post, we’ll examine The 10 Most Common C Interview Questions On Strings.

1. Find its first non-repeating character

Problem Statement

Given a string, find the first non-repeating character in it.

Examples:

Input: "abccad"
Output: The first non-repeating character is 'b'

Solution

1. Create a count array with the maximum number of characters i.e 256. This array can be initialised to -1. 
2. Then, loop
through the string character-by-character and verify that the element in this array with this index is -1. 
3. If it's -1, then change it back to index of character in string i.e i.
4. If it's not -1, then the character has already been used before, thus change it to -2.

5. All repeating characters will be changed into -2 at the end. Non-repeating characters will include the index wherever they occur.
6.We can now loop through all non-repeating characters to find the minimum index, or the first index.

Implementation

// C Interview Questions On Strings: Find its first non-repeating character

#include <stdio.h>
#include <string.h>
#include <limits.h>

int firstNonRepeating(char * str) {
  int frequency_array[256];

  for (int i = 0; i < 256; i++)
    frequency_array[i] = -1;

  for (int i = 0; i < strlen(str); i++) {
    if (frequency_array[str[i]] == -1) {
      frequency_array[str[i]] = i;
    } else {
      frequency_array[str[i]] = -2;
    }
  }

  int first_repeating_index = INT_MAX;

  for (int i = 0; i < 256; i++) {

    // If this character is not -1 or -2 then it
    // means that this character occurred only once
    // so find the min index of all characters that
    // occur only once, that's our first index

    if (frequency_array[i] >= 0)
      first_repeating_index = first_repeating_index < frequency_array[i] ? first_repeating_index : frequency_array[i];
  }

  // if res remains INT_MAX, it means there are no
  // characters that repeat only once or the string is empty
  if (first_repeating_index == INT_MAX) return -1;
  else return first_repeating_index;
}

2. Distinct character in a given string

Problem Statement

Given an character array, print all distinct elements in array. The given array may contain duplicates and the output should print every character only once.

Examples:

Input: "abccad"
Output: All distinct elements are 'a','b','c,'d'

Solution

1. Create a count array with the maximum number of characters i.e 256. This array can be initialised to -1. 
2. Then, loop
through the string character-by-character and verify that the element in this array with this index is -1. 
3. If it's -1, then change it to 0 and print the character.
4. If it's not -1, then it means that the character has already been used before, thus ignore.

Implementation

// C Interview Questions On Strings: Distinct Elements In An Array 

#include <stdio.h>
#include <string.h>
#include <limits.h>

void distinctelements(char * str) {
  int frequency_array[256];
  for (int i = 0; i < 256; i++)
    frequency_array[i] = -1;

  for (int i = 0; i < strlen(str); i++) {
    if (frequency_array[str[i]] == -1) {
     frequency_array[str[i]] = 0;
      printf("%c ",str[i]);
   }
  }
}

3. Reverse words in a given string

Problem Statement

Let the input string be “C Interview Questions on Strings”. The function should change the string to “StringsonQuestionsInterviewC”

Examples:

Input: arr[] = “C Interview Questions on Strings”.
Output: “Strings on Questions Interview C”

Solution

1. Reverse each word of the string one at a time, in the example above.
After reversed individual words, the string will be "C veiwretnI sonitseuQ no sgnirtS".
2. Reverse the entire string from end to beginning to produce the output you wantStringsonQuestionsInterviewC”

Implementation

// C Interview Questions On Strings: Reverse words in a given string

void reverse(char* begin, char* end)
{
    char temp;
    while (begin < end) {
        temp = *begin;
        *begin++ = *end;
        *end-- = temp;
    }
}

void reverseWords(char* s)
{
    char* start = s;
    char* temp = s;
    while (*temp) {
        temp++;
        if (*temp == '\0') {
            reverse(start, temp - 1);
        }
        else if (*temp == ' ') {
            reverse(start, temp - 1);
            start = temp + 1;
        }
    }
    reverse(s, temp - 1);
    printf("%s", s);
    
}

4. Write your own atoi()

Problem Statement

It is the atoi() function in C uses the string (which is the number) in its argument, and then returns the value as an integer of type. This function converts the argument string into an integer.

Examples:

Input: "12546"
Output: 123456
Note: Here input is of string type and output is of integer type. 

Solution

1. If the string starts with "-", then save the character in variable as negative. Initialise the result to zero.
2.Start with the first character and then update the results for each character.
3.Each time a character is changed, the result is results * 10 +(str[i] - '0') .
4.Multiply the stored sign with the result.

Implementation

// C Interview Questions On Strings: Write your own atoi()

int myAtoiFunction(char * str) {
  int result = 0;

  // Initialize sign as positive
  int sign = 1;

  // Initialize index of first digit
  int i = 0;

  // Ignore Leading whitespace
  while (str[i] == ' ')
    i++;

  // If number is negative,
  // then update sign
  if (str[i] == '-') {
    sign = -1;

    // Also update index of first digit
    i++;
  }

  // Iterate through all digits
  // and update the result
  for (; str[i] != '\0'; ++i)

    // Ignore trailing spaces
    if (str[i] != ' ')
      result = result * 10 + str[i] - '0';

  // Return result with sign
  return sign * result;
}

5. Reverse a string in c without using a library function

Problem Statement

C provides inbuilt library function called strrev() function to reverse the string. But the problem statements stats that without using any library function reverse a string. So, we need to write our own strrev function.

Examples:

Input: HelloWorld
Output: dlroWolleh

Solution

The idea is to use two pointers one will start from beginning and other from end. Keep swapping start pointer crosses end pointer.

Implementation

// C Interview Questions On Strings: Reverse a string in c without using a library function

void reverseString(char * str) {

  int start = 0;
  int end = 0;

  // Get the length of String
  while (str[end++] != '\0');

  // Remove the null character and since indexing starts 
  // from 0 end will point to string length - 1
  end -= 2;

  // Iterate loop upto start not equal to end
  while (start < end) {

    // Swap the two characters
    char tmp = str[start];
    str[start] = str[end];
    str[end] = tmp;
    ++start;
    --end;

  }

  printf("%s", str);
}

6. Check If String Is Palindrome

Problem Statement

If you have a string, write an c function that checks whether the string is palindrome. A string is considered to be palindrome if the reverse on the string identical as the string. For instance, “malayalam” is palindrome but “malayalan” is not palindrome.

Examples:

Input: "malayalam"
Output: 1
Input: "teachingbee"
Output: 0

Solution

1. The idea is to use two pointers one will start from beginning and other from end.
2. Keep comparing if str[start] is equal to str[end]
. If not equal return false.
3. If all the characters are matched successfully return true.

Implementation

// C Interview Questions On Strings: Check If String Is Palindrome

int checkPalindrome(char * str) {

  int start = 0;
  int end = 0;

  // Get the length of String
  while (str[end++] != '\0');

  // Remove the null character and since indexing starts 
  // from 0 end will point to string length - 1
  end -= 2;

  // Iterate loop upto start not equal to end
  while (start < end) {

    if (str[start] == str[end]) {
      ++start;
      --end;
    } else
      return 0;
  }

  return 1;
}

7. Find all permutations of String

Problem Statement

A permutation of string is refered to all the different arrangements of characters of string possible.  A string with a length of is n, has the number n! permutation.

Examples:

Input:PQR
Output: PQR QPR RPQ PRQ QRP RQP

Solution

The idea is to use backtracking.

Implementation

// C Interview Questions On Strings: Find all permutations of String

void swap(char *x, char *y) 
{ 
    char temp; 
    temp = *x; 
    *x = *y; 
    *y = temp; 
} 
  
void permute(char *str, int start, int end) 
{ 
    int i; 
    if (start == end) 
        printf("%s\n", str); 
    else
    { 
        for (i = start; i <= end; i++) 
        { 
            swap((str + start), (str + i)); 
            permute(str, start + 1, end); 
  
            //backtrack 
            swap((str + start), (str + i)); 
        } 
    } 
} 

8. Check if strings are rotations of each other or not

Problem Statement

Given a string s1 and a string s2, write a snippet to say whether s2 is a rotation of s1? 

Examples:

Input:  str1 = "ABACD"
        str2 = "CDABA"
Output: True

Input:  str1 = "ABACD"
        str2 = "DCABA"
Output: False

Solution

1. Firstly, we need to ensure both input strings are of equal length. If no, simply return false.
2. Then, Create a new string concatinated_str= str1+str1 (ABACDABACD).
3. Lastly, search if str2 is present is newly created string.
4. This algorithm works because if str2 is rotation of str1, then str1+str1 will definitely form the str2.

Implementation

// C Interview Questions On Strings: Check if strings are rotations of each other or not

# include <stdio.h>
# include <string.h>
# include <stdlib.h>


int checkRotations(char* str1, char* str2)
{
  int str1_length   = strlen(str1);
  int str2_length   = strlen(str2);
 
  /* Check if sizes of two strings are same */
  if (str1_length != str2_length)
     return 0;
 
  /* Create a temp string with value str1.str1 */
 char * concatinated_str   = (char *)malloc(sizeof(char)*(str1_length*2 + 1));
  strcat(concatinated_str, str1);
  strcat(concatinated_str, str1);
 
  /* Check if str2 is a substring of concatinated_str */
  void *ptr = strstr(concatinated_str, str2);
 
  free(concatinated_str); // Free dynamically allocated memory
 
  /* strstr returns NULL if the second string is NOT a
    substring of first string */
  if (ptr != NULL)
    return 1;
  else
    return 0;
}
 

9. Count a number of vowels and consonants in a String

Problem Statement

Given a String count number of vowels and consonants in string.

Examples:

Input: "abcuidw"
Output: Vowels = 3
        Consonants = 4

Solution

1. Traverse through string's character one by one, maintaining two variable counts, one for vowels other for consonants.
2.Check if is either of a,e,i,o,u
. If yes, increment vowels count variable else consonant count.

Implementation

// C Interview Questions On Strings: Count a number of vowels and consonants in a String

# include <stdio.h>
# include <string.h>

void count_vowels_consonants(char * s) {
  int vcount = 0;
  int ccount = 0;

  for (int i = 0; s[i]; i++) {
    //Check if it is alphabet or not
    if ((s[i] >= 65 && s[i] <= 90) || (s[i] >= 97 && s[i] <= 122)) {

      if (s[i] == 'a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'o' || s[i] == 'u' || s[i] == 'A' || s[i] == 'E' || s[i] == 'I' || s[i] == 'O' || s[i] == 'U')
        vcount++;
      else
        ccount++;
    }

  }
  printf("Vowels: %d\nConsonants: %d", vcount, ccount);
}

10. Search for a pattern in a given string

Problem Statement

Given a string str[] of length n and a pattern pat[] of length m, write a function  that prints all occurrences of pat[] in str[].

Examples:

Input:  str[] =  "AABAACAADAABAABA"
        pat[] =  "AABA"
Output: Pattern is present at index 0
        Pattern is present at index 9
        Pattern is present at index 12

Solution

Slide the pattern over text one by one and check for a match. If a match is found, then slides by 1 again to check for subsequent matches. 

Implementation

// C Interview Questions On Strings: Search for a pattern in a given string

#include <stdio.h>
#include <string.h>
 
void pattern_matching(char* pat, char* str)
{
    int M = strlen(pat);
    int N = strlen(str);
 
    /* A loop to slide pat[] one by one */
    for (int i = 0; i <= N - M; i++) {
        int j;
 
        /* For current index i, check for pattern match */
        for (j = 0; j < M; j++)
            if (str[i + j] != pat[j])
                break;
 
        if (j == M)
            printf("Pattern found at index %d \n", i);
    }
}

The number of comparisons made here are in the worst case scenario is O(m*(n-m+1)). The KMP matching algorithm improves the worst case to O(n).

Conclusion

In this article we covered various types of c interview basic questions on Strings. Hope you all got idea about common c interview questions on strings usually asked.

Got a question or just want to chat? Comment below or drop by our forums, where a bunch of the friendliest people you’ll ever run into will be happy to help you out!

90% of Tech Recruiters Judge This In Seconds! 👩‍💻🔍

Don’t let your resume be the weak link. Discover how to make a strong first impression with our free technical resume review!

Related Articles

data mining functionalities

What are Data Mining Functionalities?

Introduction In this article we will look into various data mining functionalities. Data Mining is the process of extracting information from raw data to identify patterns, trends, and useful data

Why Aren’t You Getting Interview Calls? 📞❌

It might just be your resume. Let us pinpoint the problem for free and supercharge your job search. 

Newsletter

Don’t miss out! Subscribe now

Log In