Skip to content
Tutorials Center
My learning

Topics

Lesson 131 of 135 ยท Practice and Review

More C String Programs

More string programs in C with output: add binary strings, first non-repeating character, pangram check, word initials, strip leading zeros, insert, split and compare.

C Programs: 50 Classic Examples covers reversing, palindromes, anagrams and run-length encoding. This page adds eight more string classics that interviews and exams keep returning to. Each one is a small function that you can drop into your own code, plus a main that proves it works.

All of them follow the same safety rules as the rest of the track: a string is a char array ending in '\0', every write goes into a buffer whose size you know, and anything passed to a <ctype.h> function is cast to unsigned char first. See Strings and String Safety if those rules are new.

Add two binary strings

Add the bits from the right, carrying as you go, and build the answer backwards in a buffer. The buffer needs room for one more digit than the longer input, plus the terminator.

C Add two binary strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Digits are converted with c - '0', which works because the codes of '0' to '9' are consecutive. The loop keeps going while there is a carry left, so 1111 + 1 grows to five digits. After the loop memmove shifts the finished digits to the front of the buffer, including the terminator. The function assumes the buffer is big enough; a production version would check k before each write.

First non-repeating character

Count how often each byte occurs, then scan the string again and return the first character whose count is 1. Two passes beat comparing every pair.

C First non-repeating character

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The function returns an int so it can use EOF for "no such character", the same trick getchar uses. swiss gives w, level has v as its only unique letter, and in programming the first letter that appears once is p.

Pangram check

A pangram contains every letter of the alphabet at least once. Keep a 26-bit mask and set a bit for each letter you see; the sentence is a pangram when all 26 bits are set.

C Pangram check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

isalpha only matches ASCII letters in the default "C" locale, so the shift amount is always between 0 and 25. The expression (1u << 26) - 1 is a number with 26 one-bits. See Bitwise Operators.

Initials: the first letter of each word

A letter starts a word when it is not a space and the character before it is a space (or the string start). Tracking "was the previous character a space?" in one variable does it in one pass.

C First letter of each word

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The extra spaces in the first example do no harm, because the flag only changes at the transition from space to letter.

Remove leading zeros

Skip the zeros, but stop one character early so "0000" becomes "0" instead of an empty string. Then move the rest down with memmove, which handles overlapping memory correctly.

C Remove leading zeros

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Insert one string into another

Inserting means opening a gap: move the tail of the target to the right by strlen(insert) bytes, then copy the new text into the gap. Check that the result fits first.

C Insert a string at a position

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Returning a bool lets the caller see the refusal. Using memmove here is essential: the source and destination ranges overlap, and memcpy would be undefined behavior.

Split a string by a delimiter

strtok modifies its input and keeps hidden state, so it is awkward in real programs. A safer pattern uses strchr to find each delimiter and prints (or copies) the piece in between, leaving the original untouched. Unlike strtok, it also reports empty fields.

C Split by a delimiter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The format %.*s prints at most length characters taken from the argument list, so no copy and no terminator are needed. The empty third field shows as "".

Compare strings lexicographically

strcmp returns a negative number, zero or a positive number. Writing it yourself shows what that means: walk both strings while the characters match, then compare the first difference as unsigned char values.

C Your own strcmp

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

A prefix is smaller than the longer string because the shorter one reaches '\0' (value 0) first. Only the sign of the result is specified for the real strcmp, so compare it against 0 and never print or depend on the exact number.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the first-unique program return an int instead of a char?

    Every byte value is a possible answer, so a separate out-of-range value such as EOF is needed to say there is none.
  2. 2. Why must insert_at use memmove and not memcpy to shift the tail?

    memcpy has undefined behavior when source and destination overlap. memmove is defined to copy as if through a temporary buffer.
  3. 3. What does the format "%.*s" take from the argument list?

    The * after the dot means the precision is passed as an int argument just before the string.
  4. 4. In strip_leading_zeros, why does the loop test s[skip + 1] != '\0'?

    The loop stops on the last character, so a string made only of zeros becomes a single "0".

Summary

  • Digit characters convert with c - '0'; letters map to 0-25 with tolower(c) - 'a'.
  • A 256-entry count array (indexed by unsigned char) makes character-frequency problems two passes.
  • A bit mask is a compact set: one bit per letter makes the pangram test a single comparison.
  • Insert, delete and strip operations shift memory with memmove, because the ranges overlap.
  • Split with strchr and %.*s to keep the input intact and keep empty fields; compare strings by the first differing unsigned char.

Next: C Practice Exercises, where you write programs like these yourself.