LearnFrenzy
Sign in Take a free test
C

C Programming · Topic 6 of 23

Strings Questions and Concepts

  • 4 exercises
  • 40 questions
  • ~60 min
  • Answers explained

Coding Techniques

Strings · Study material

Frequency table with int[256]

Count characters with one array indexed by the byte value. It solves anagrams, first-unique-character and most-frequent-character problems in O(n).

#include <stdio.h>

int main(void) {
    const char *s = "mississippi";
    int count[256] = {0};                     /* one counter per byte value */
    for (const char *p = s; *p; p++)
        count[(unsigned char) *p]++;          /* the cast keeps the index 0..255 */

    int best = 0;
    for (int c = 1; c < 256; c++)
        if (count[c] > count[best])
            best = c;
    printf("most frequent: '%c' (%d times)\n", best, count[best]);
    return 0;
}

Output

most frequent: 'i' (4 times)

The (unsigned char) cast matters: a negative char would index before the array.

In-place filtering with a read and a write pointer

To delete characters without a second buffer, read with one pointer and write with another that only moves when a character is kept. End with a new terminator.

#include <stdio.h>

void remove_spaces(char *s) {
    char *w = s;                              /* write pointer */
    for (const char *r = s; *r; r++)          /* read pointer */
        if (*r != ' ')
            *w++ = *r;
    *w = '\0';                                /* end the shorter string */
}

int main(void) {
    char s[] = "a b  c d";
    remove_spaces(s);
    printf("%s\n", s);
    return 0;
}

Output

abcd

Bounded copies and joins

Prefer one snprintf() over chains of strcpy() and strcat(): it knows the buffer size, always terminates, and reports truncation.

char full[64];
int n = snprintf(full, sizeof full, "%s %s", first, last);
if (n < 0 || (size_t) n >= sizeof full) {
    /* the name did not fit: handle it instead of silently cutting it */
}

When you must use strncpy(d, s, n), add d[n - 1] = '\0'; yourself.

Parsing numbers with strtol()

atoi() cannot report errors: "abc" and "0" both give 0. strtol() tells you where parsing stopped and sets errno on overflow.

char *end;
errno = 0;
long v = strtol(text, &end, 10);
if (end == text)            puts("no digits");
else if (*end != '\0')      puts("extra characters after the number");
else if (errno == ERANGE)   puts("out of range");

Safe string habits

  • Size buffers as length + 1, and use sizeof buf, not a repeated number.
  • Read lines with fgets(); never gets().
  • Use %15s (a width) if you must use scanf("%s").
  • Point to literals with const char *.
  • Compare with strcmp(); test strchr()/strstr() results for NULL.
  • Pass (unsigned char) c to ctype functions.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About C Programming

C programming is the language most computer science courses start with and the foundation of operating systems, embedded devices and compilers. This section helps you learn C properly – data types, operators, control statements, functions, arrays, strings, pointers, structures, memory allocation and files – and then prove it with hundreds of practice questions explained line by line.

Why it matters

  • C teaches how a computer really works: memory, addresses and how data is stored
  • Pointers and memory questions are a favourite in written tests and technical interviews
  • Once you know C, learning C++, Java and Python becomes much easier
  • Embedded systems, operating systems and many companies' coding rounds still use C

Who it is for

  • School students (Class 11–12 computer science) building a strong programming base
  • College students (B.Tech, BCA, MCA, B.Sc CS) preparing for semester exams, lab work and viva
  • Freshers preparing for campus placements, aptitude-cum-coding tests and technical interviews
  • Anyone preparing for GATE CS or government IT exams

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • TCS, Infosys, Wipro tests
  • Technical interviews
  • GATE CS
  • University exams
  • Government IT exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links