0

C String and Character Functions Samples

Here are the exercises I did for the string and character functions:

/*
 *
 * exercise1.c
 *
 * Allow user to input a string from the keyboard and
 * display the ASCII value for each character
 *
 * by Robby Chen, 2010
 *
 */

#include <stdio.h>

main() {
 char string[51];
 int character;

 puts(""); // Prints a new line
 fputs("Please enter a string (less than 50 characters, including spaces): ", stdout); // Does not add the new line at the end
 fgets(string, 51, stdin);
 puts("");
 puts("Character ASCII Value");
 puts("-------------------------");

 for (character = 0; string[character] != ''; character++) {
  if (string[character] == 'n') { // prints the new line character and its ASCII code
   printf("    \n%12dn", string[character]);
  }
  else { // prints individual letters of the string and their ASCII codes
   printf("%5c %12dn", string[character], string[character]);
  }
  puts("-------------------------");
 }

 puts("");
 fflush(stdin);
}

Note that the above code contains ASCII-related technique. You can read more about ASCII characters set here if you haven’t already done so above.

/*
 *
 * exercise2.c
 *
 * Allow users to enter their names from the keyboard
 * and output the names with upper case on the first letter
 * and lower case on the other letters of each word
 *
 * by Robby Chen, 2010.
 *
 */

#include <stdio.h>
#include <ctype.h>

main() {
 char name[51];
 int letter;

 fputs("Please enter your name: ", stdout);
 fgets(name, 51, stdin);

 fputs("Hello, ", stdout);

 for (letter = 0; name[letter] != ''; letter++) {
  if (letter == 0 || isspace(name[letter - 1])) {
   name[letter] = toupper(name[letter]);
   printf("%c", name[letter]);
  }
  else {
   name[letter] = tolower(name[letter]);
   printf("%c", name[letter]);
  }
 }

 fflush(stdin);
}