Accessing Characters in a String

The following program shows three ways of writing the code that translates each character in a string to upper case. This is a study in efficiency.

They all do the same thing, but some of the methods are slower.

The Program

/********************************************* ** File: quicker.c ** Author: S. Bogar ** Date: 8/8/96 ** Modified: 9/26/05 ** Section: 101 ** EMail: bogar@cs.umbc.edu ** ** Quicker ways to access the characters in a string. ********************************************** / #include <stdio.h> #include <string.h> #include <ctype.h> int main() { int i, length ; char c, str[31] = "this line is all in upper case" ; /* This is a fast way */ printf("Method 1: ") ; for(i = 0; str[i] != '\0'; i++) { c = str[i] ; c = toupper(c) ; printf("%c", c) ; } printf("\n\n") ; /* This is slightly slower, but okay to use */ printf("Method 2: ") ; length = strlen(str) ; for(i = 0; i < length; i++) { c = str[i] ; c = toupper(c) ; printf("%c", c) ; } printf("\n\n") ; /* This is the slowest - Don't use this method! */ printf("Method 3: ") ; for(i = 0; i < strlen(str); i++) { c = str[i] ; c = toupper(c) ; printf("%c", c) ; } printf("\n\n") ; return 0; }

The Sample Run

Method 1: THIS LINE IS ALL IN UPPER CASE Method 2: THIS LINE IS ALL IN UPPER CASE Method 3: THIS LINE IS ALL IN UPPER CASE
Last Modified -