DMP - Chapter 11
Character String and String functions
String constants
#include < stdio.h>
void main(void)
{
printf("%s, %p, %c\n", "We", "love", *"snow");
}
String arrays and initialization
char m1[] = "We love snow";
char m1[] = {'W', 'e', ' ', 'l', 'o', 'v', 'e', ' ', 's', 'n', 'o', 'w', '\0'};
m1 == &m1[0], *m1 == 'W', *(m1 + 1) == m1[1] == 'u'
char *m2 = "We love snow";
Array vs pointer
Arrays of strings
char *m3[3] = {"We", "love", "snow"}; (ragged array)
char m4[3][4] = {"We", "love", "snow"}; (rectangular array)
Pointers and strings
#include < stdio.h>
void main(void)
{
static char * mesg = "Don't be a fool!";
static char * copy;
copy = mesg;
printf("%s\n", copy);
printf("mesg= %s &mesg= %p; value= %p\n",
mesg, &mesg, mesg");
printf("copy= %s &copy= %p; value= %p\n",
copy, &copy, copy");
}
String input
String output
Do-it-yourself
- Write a function that prints a string and counts characters
String functions
- strlen()
- strcat()
- strcmp()
- strcpy()
- sprintf()
- Others: strncpy(), strncat(), strncmp(), strchr(), strpbrk(), strrchr(), strstr()
Sorting strings
/* Listing 11.22 -- string-pointer-sorting function */
vodi ststr(char *strings[], int num)
{
char *temp;
int top, seek;
for (top = 0; tom < num - 1; top++)
for (seek = top + 1; seek < num; seek++)
if (strcmp(strings[top], strings[seek]) > 0)
{
temp = strings[top];
strings[top] = strings[seek];
strings[seek] = temp;
}
}
The ctype.h character functions
- isalnum(), isalpha(), iscntrl(), isdigit(), isgraph(), islower(),
- isprint(), ispunct(), isspace(), isupper(), isxdigit()
Command-line arguments
#include < stdio.h>
void main(int argc, char *argv[])
{
int i;
for (i = 0; i < argc; i++)
printf("%d: %s\n", argv[i]);
printf("\n");
}
For ThinkC
#include < stdio.h>
#include < console.h>
void main(int argc, char *argv[])
{
int i;
argc = ccommand(&argv);
for (i = 0; i < argc; i++)
printf("%d: %s\n", argv[i]);
printf("\n");
}
String-to-number conversions
- atoi(), atof(), atol(). /* #inculde stdlib.h */
- For number-to-string, use sprintf()
Assignment #13: Due Feb 1
Write a program that accepts any number of notes in pitch-octave notation, e.g., a4, gs5, df3, on the command line then prints out, in ascending order of pitches, the original name, their pitch in frequency, MIDI number, and its pitch class (0-11). Do not use malloc().
The output should look like:
df3 300 49 1
a4 440 69 9
gs5 850 80 8
Assignment #12: Due Jan. 23
Go to Ich's Home Page
Go to the Peabody Home Page
For comments or questions email to:
ich@peabody.jhu.edu