WeCodeAcademy

C Character and String Helpers

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

int main(void) {
  char text[] = "Hello, World 42!";
  int letters = 0, digits = 0, spaces = 0;
  for (int i = 0; text[i] != '\0'; i++) {
    if (isalpha((unsigned char)text[i])) letters++;
    else if (isdigit((unsigned char)text[i])) digits++;
    else if (isspace((unsigned char)text[i])) spaces++;
  }
  printf("letters=%d digits=%d spaces=%d\n", letters, digits, spaces);

  for (int i = 0; text[i]; i++) text[i] = toupper((unsigned char)text[i]);
  printf("%s\n", text);

  printf("%d\n", atoi("123") + 1);
  printf("%.1f\n", atof("2.5") * 2);
  char *comma = strchr(text, ',');
  printf("comma at %ld\n", (long)(comma - text));
  return 0;
}
Output
letters=10 digits=2 spaces=2
HELLO, WORLD 42!
124
5.0
comma at 5

<ctype.h> tests and converts single characters; atoi and atof turn text into numbers.

Quick check

Which function turns the text "123" into the number 123?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.