UMBC CS 201, Fall 98
UMBC CMSC 201 & 201H Fall '98 CSEE | 201 | 201 F'98 | lectures | news | help

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 Quicker ways to access the characters in a string. */ #include <stdio.h> #include <string.h> #include <ctype.h> 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 */ 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 */ printf("Method 3: ") ; for (i = 0 ; i < strlen(str) ; i++) { c = str[i] ; c = toupper(c) ; printf("%c", c) ; } printf("\n\n") ; }

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


CSEE | 201 | 201 F'98 | lectures | news | help

Last Modified - Monday, 26-Oct-1998 11:56:03 EST