string Interview questions in C

Top 15 string Interview Questions in C, might ask by the interviewer.

If you are looking for “string Interview Questions in C”,  then you are at right place. Here you will find some solved and unsolved string Interview Questions in C. For the interviewer, string questions are fascinating generally interviewer ask the questions related to the string algorithm. So here I am creating a collection of some important string interview questions in C that might ask by your interviewer.

Remove all duplicates from a given string

Suppose you have a string “silence is a source of great strength” when we will remove the duplicate character from the string then the output will be “silenc aourfgth“.

Steps to check the duplicate character in a given string:

 

1. Initialize the required variable

pString = “silence is a source of great strength” ;/* input string */

startIndex = 0 ;/* index of next character in input string */

resultIndex = 0; /* index of next character in resultant string */

binTable[255] = {0}; /* Binary table to check the duplicate character */

2. Create a loop that runs until the end of the string (till the null character).

3. We know that every character has the ASCII value, so mark the index of binTable for the unique ASCII value,

for example,

Suppose if input string is pString ,
pString = “silence is a source of great strength” ; /* input string */

Get the character from the string ( pString )

binTableIndex = *(pString + startIndex);

If the character is unique then,

marked binTable for startIndex,
*(pString + startIndex) = MARK_USED;

Copy the *(pString + startIndex) character in resultant string.
*(pString + resultIndex) = *(pString + startIndex);

increment the resultIndex,
resultIndex++;

Increment the startIndex,
startIndex++;

If the character is not unique then,

Only increment the startIndex,
startIndex++;

Again go to read next character until not get the null character.

Assigned the null character in the last of the resultant string to remove the extra character.*(pString+resultIndex) = ‘\0’;

 

For the better understanding see the below code,

 

#include <stdio.h>


#define SIZE_BIN_TABLE 256
#define UNIQUE_CHARACTER 0
#define MARK_USED 1


/* Removes duplicate characters from the Input string */

char *RemoveDupChar(char *pString)
{

    short  binTable[SIZE_BIN_TABLE] = {0}; //Bin table

    int startIndex = 0, resultIndex = 0; // Index

    unsigned char binTableIndex = 0;

    while (*(pString + startIndex)) //Till not get null character
    {
        binTableIndex = *(pString + startIndex); //get character from startIndex

        if (binTable[binTableIndex] == UNIQUE_CHARACTER) //check unique character
        {
            binTable[binTableIndex] = MARK_USED; //Marked the binTableIndex

            *(pString + resultIndex) = *(pString + startIndex); //copy character in result string

            resultIndex++;
        }
        startIndex++;
    }

    *(pString+resultIndex) = '\0'; //Assign null character to remove extra character

    return pString;
}


int main()
{
    char pString[]  =  "silence is a source of great strength"; //input string

    char *pResultString = RemoveDupChar(pString); //Remove duplicate

    printf("%s", pResultString ); //print result string

    return 0;
}

Output: silenc aourfgth

 

Reverse words in a given string

This question generally asks by an interviewer, in this question you need to reverse the words of the string, for example, if your input string is “How are you”, the output will be “you are How”.

Steps to reverse words in a given string

  • First, you need to reverse the individual words, for example,
    If an input is “How are you”, the output will be “woH era uoy”.
  • Now, reverse the whole string and you will get “you are How”.

 

For the better understanding see the below code,

 

#include<stdio.h>

//function prototype to reverse
//the string from begin to end
void revString(char *pBegin, char *pEnd)
{
    char temp;

    while (pBegin < pEnd)
    {
        temp = *pBegin;

        *pBegin++ = *pEnd;

        *pEnd-- = temp;
    }
}

// Function to reverse words
void revWord(char *pString)
{
    // store the beginning address of word
    char *word_begin = NULL;

    //word_boundary is for word boundary
    char *word_boundary = pString; /* */

    //Loop to reverse the character of words
    while( *word_boundary )
    {
        //This condition is to make sure that
        //the string start with valid character
        if (( word_begin == NULL ) && (*word_boundary != ' ') )
        {
            word_begin = word_boundary;
        }
        if(word_begin && ((*(word_boundary+1) == ' ') || (*(word_boundary+1) == '\0')))
        {
            revString(word_begin, word_boundary);
            word_begin = NULL;
        }
        word_boundary++;
    }
    // reverse the whole string
    revString(pString, word_boundary-1);
}




int main()
{
    //source string
    char src[] = "How are you";

    //Reverse the word of the string
    revWord(src);

    //print the resultant string
    printf("Resultant string = %s", src);

    return 0;
}

Output: you are how

 

Searching for a pattern in a given string

Sometimes interviewer asks the question to search a pattern in a given string. There are a lot of algorithms to find the pattern, later we will discuss all the algorithms in detail. Here I am using the Naive algorithm (not a smart algorithm) to search a Pattern.

Suppose a given source string is src[0..n-1] and a pattern is pat[0..m-1]. Here to search the pattern for a given string, we need to slide the pattern string (pat) over source string (src) one by one and check for the match. If the match is found, then slides by 1 again to check for subsequent matches.

Example,
Input: src[] = “How are you”
Patteren: pat[] = “are”
Output: Pattern found at index 4

 

For the better understanding see the below code,

 

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

//Function to search the pattern
void searchPattern(char *pSrcString, char* pPattern)
{
    int lenSrcString = strlen(pSrcString); //Get length of src string

    int lenPatString = strlen(pPattern); //Get length of pattern string

    int srcIndex = 0;

    /* A loop to slide pat[] one by one on src*/
    for (srcIndex = 0; srcIndex <= lenSrcString - lenPatString; ++srcIndex)
    {
        int patternIndex;

        /* For current index i, check for pattern match */
        for (patternIndex = 0; patternIndex < lenPatString; ++patternIndex)
        {
            if (pSrcString[srcIndex + patternIndex] != pPattern[patternIndex])
                break;
        }

        // if pat[0...M-1] = src[srcIndex, srcIndex+1, ...srcIndex+M-1]

        if (patternIndex == lenPatString)
        {
            printf("Pattern found at index %d \n", srcIndex);

        }
    }
}

int main()
{
    char src[] = "How are you"; //source string

    char pat[] = "are"; //pattern you want to find

    searchPattern( src,pat); //function to search pattern

    return 0;
}

Output: Pattern found at index 4.

 

If you want to learn more about the c language, here 10 Free days C video course for you.

C tutorial

 

Write your own atoi()

The atoi() is a c library function used to convert a numeric string to his integer value.

Steps to create own atoi().

The atoi() only convert a numeric string to their integer value, so check the validity of the string. If any non-numeric character comes, the conversion will be stopped.

For more detail see this article:  create own atoi().

Subtract 48 (ASCII value of 0) from the string character to get the actual value and perform some arithmetical operation.

for example,

If the numeric string is “124”, we know that ASCII value of ‘1’, ‘2, and ‘4’ is 49, 50 and 52 respectively. So if we subtract 48 from these numeric characters we will get the actual numeric value 1,2 and 4.

 

For the better understanding see the below code,

 

#include<stdio.h>

#define Is_NUMERIC_STRING(d) (*(char*)d >= 48) && (*(char*)d<= 57)


int StringToInt(const char *pszBuffer)
{

    int result=0; // variable to store the result

    int sign = 1; //Initialize sign as positive

    if(pszBuffer == NULL) //If pointer is null
        return 0;

    //If number is negative, then update sign
    if((*pszBuffer) == '-')
    {
        sign = -1;

        ++pszBuffer; //Increment the pointer
    }
    
    while( Is_NUMERIC_STRING(pszBuffer)) //check string validity
    {
        result = (result*10)+ (*pszBuffer-48);

        pszBuffer++; //Increment the pointer
    }

    return (sign * result);
}


int main()
{
    int d;

    d = StringToInt("-1230");

    printf("%d\n",d);

    return 0;
}

Output: -1230

Reverse a string in c without using a library function

In the interview generally, Interviewer asked the question to reverse a string without using the C library function or maybe they can mention more conditions, it totally depends on the interviewer.

For more detail see this article: Reverse a string in c

Algorithm:

  • Calculate the length (Len) of string.
  • Initialize the indexes of the array.
    Start = 0, End = Len-1
  • In a loop, swap the value of pszData[Start] with pszData[End].
  • Change the indexes’ of the array as follows.
    Start = start +1; End = end – 1

 

For the better understanding see the below code,

#include <stdio.h>

int main(int argc, char *argv[])
{

    char acData[100]= {0}, Temp = 0;
    int iLoop =0, iLen = 0;

    printf("\nEnter the string :");
    gets(acData);

    // calculate length of string
    while(acData[iLen++] != '\0');

    //Remove the null character
    iLen--;

    //Array index start from 0 to (length -1)
    iLen--;

    while (iLoop < iLen)
    {
        Temp = acData[iLoop];
        acData[iLoop] = acData[iLen];
        acData[iLen] = Temp;
        iLoop++;
        iLen--;
    }

    printf("\n\nReverse string is : %s\n\n",acData);
    return 0;
}

 

 

As per suggestion, here I am giving 10 important string questions for the practice. If you have any doubt or you faced any problem, then just hit the comment button and share your problem with us. We will definitely try to solve your problem.

  1. How to check if String is Palindrome?
  2. How to find all permutations of String?
  3. A Program to check if strings are rotations of each other or not?
  4. How to count a number of vowels and consonants in a String?
  5. How to count the occurrence of a given character in String?
  6. How to return highest occurred character in a String?
  7. How to reverse String in c using Recursion?
  8. How to replace each given character to another?
  9. Left Rotation and Right Rotation of a String?
  10. calculate the sum of all numbers present in a string in c?

Recommended Post