Вы находитесь на странице: 1из 1

DAVID MALAN: Suppose we'd like to write a program that prompts the user for a st

ring and then capitalizes that string. Well, let's start with some familiar code
declaring a string called s and assigning it the return value of getstring. And
let's now proceed to iterate over the characters in this string. Well, how to d
o that? It turns out that a string is just a sequence of characters, but more pr
operly, a string is an array of characters, which means we can use square bracke
t notation to index into a string and get at individual characters.
In other words, we can do the following. For int, i gets 0, and n gets, say, the
length of s, using our function [? stir ?] [? line, ?] i is less than n i++. In
other words, with this loop, we will iterate over all n letters in the string s
. And within this loop, I'm going to check, if the i-th character in s greater t
han or equal to lowercase a, and the i-th character is less than or equal to a l
owercase c, then I want to proceed to capitalize that letter. In other words, I
want to print out %c as a placeholder and substitute in for that placeholder s b
racket i.
But then I need to convert s bracket i to uppercase. To do this, I can simply su
btract whatever the difference is between lowercase a and capital A. Well, I act
ually do recall that capital A is 65 in ASCII, and lowercase a is 97. So the dif
ference is technically 32. So I could just hard code 32 here. But I might not ne
cessarily remember those numbers.
And moreover, what if they vary by computer? Most likely they're not. But the po
int remains that I can still generalize that arithmetic expression as just whate
ver the difference is between a lowercase a and a capital A is what I want to su
btract off from this particular lowercase letter.
Now, if this particular letter is not lowercase, I simply want to print it out.
printf, %c as my placeholder, s bracket i. At the bottom of this program, let's
simply print out newline so that my prompt appears on a new line of its own.
Let's now compile this program with make capitalize0. Let's run it with capitali
ze0. And let's type in a word like hello in all lowercase. I get back HELLO in u
ppercase as expected. But let's try one more test, this time with my own name, D
-A-V-I-D, but with the first D capitalized, just in case I messed something up w
ith that first char. Enter, and D-A-V-I-D in uppercase is printed as well.

Вам также может понравиться