String Interview Questions

Importance of String Interview Questions : String is the most important class in C, C++ and Java. There can be hardly any  interview without a question about String. String objects are treated as special in programming languages which makes it an interesting candidate for all interviews. In this post we will see some of the frequently asked Java String interview questions and answers for freshers and also for experienced programmers. Knowing answers to these questions will be very helpful to tackle any questions asked related to String in interview.

 

QUESTION-1 Find the Frequency of Characters.

Answer-
int main()
{
   char str[1000], ch;
   int i, freQuency = 0;
   printf("Enter a string: ");
   gets(str);
   printf("Enter a character to find the frequency: ");
   scanf("%c",&ch);
   for(i = 0; str[i] != '\0'; ++i)
   {
       if(ch == str[i])
           ++freQuency;
   }
   printf("Frequency of %c = %d", ch, frequency);
   return 0;
}

 

QUESTION-2 Program to count vowels, consonants etc.

Answer-
int main()
{
    char line[150];
    int i, vowels, consonants, digits, spaces;

    vowels =  consonants = digits = spaces = 0;

    printf("Enter a line of string: ");
    scanf("%[^\n]", line);

    for(i=0; line[i]!='\0'; ++i)
    {
        if(line[i]=='a' || line[i]=='e' || line[i]=='i' ||
           line[i]=='o' || line[i]=='u' || line[i]=='A' ||
           line[i]=='E' || line[i]=='I' || line[i]=='O' ||
           line[i]=='U')
        {
            ++vowels;
        }
        else if((line[i]>='a'&& line[i]<='z') || (line[i]>='A'&& line[i]<='Z')) { ++consonants; } else if(line[i]>='0' && line[i]<='9')
        {
            ++digits;
        }
        else if (line[i]==' ')
        {
            ++spaces;
        }
    }

    printf("Vowels: %d",vowels);
    printf("\nConsonants: %d",consonants);
    printf("\nDigits: %d",digits);
    printf("\nWhite spaces: %d", spaces);

    return 0;
}

 

QUESTION-3 Reverse a sentence using recursion.

Answer-
void reverseSentence();

int main()
{
    printf("Enter a sentence: ");
    reverseSentence();

    return 0;
}

void reverseSentence()
{
    char c;
    scanf("%c", &c);

    if( c != '\n')
    {
        reverseSentence();
        printf("%c",c);
    }
}

 

QUESTION-4 Calculate Length of String without Using strlen() Function.

Answer-
 
int main()
{
    char s[1000], i;

    printf("Enter a string: ");
    scanf("%s", s);

    for(i = 0; s[i] != '\0'; ++i);

    printf("Length of string: %d", i);
    return 0;
}

 

QUESTION-5 Concatenate Two Strings Without Using strcat().

Answer-
 
int main()
{
    char s1[100], s2[100], i, j;

    printf("Enter first string: ");
    scanf("%s", s1);

    printf("Enter second string: ");
    scanf("%s", s2);

 
    for(i = 0; s1[i] != '\0'; ++i);

    for(j = 0; s2[j] != '\0'; ++j, ++i)
    {
        s1[i] = s2[j];
    }

    s1[i] = '\0';
    printf("After concatenation: %s", s1);

    return 0;
}