Sie sind auf Seite 1von 9

Character Data

This course focuses on only three primitives:


int, double and char (character).

CS1010E Lecture 10

A character value is enclosed in single quotes, such as


A, b, and 3.

Character Strings
Two Dimensional Arrays

A character value (just like integer) is an integral type;


can be used within a switch control expression.

Henry Chia
hchia@comp.nus.edu.sg

Each character value is mapped to a unique integer


value following the ASCII table.

Semester 1 2011 / 2012


Department of Computer Science

There are 128 characters.

School Of Computing

Because characters and integers are alike, they can be


arithmetically manipulated.

National University Of Singapore

CS1010E Lecture 10 p.1/33

CS1010E Lecture 10 p.3/33

Character Ordering

Lecture Outline
Characters

digit-chars

uppercase-chars

lowercase-chars

Character ordering

digit-chars: 0, 1, . . . , 9.

Declaring variable and arrays

uppercase-chars: A, B, . . . , Z.

lowercase-chars: a, b, . . . , z.

Strings

Others: control characters and punctuations.

String definition
String functions

Character arithmetic
A+1 B ; c-a 2 ; 9-0 9

Two dimensional arrays

(d-a)+A D (i.e. case conversion)

Declaration and initialization


Passing into functions

Character relations

Passing rows as 1D arrays

0 < 9 < A < Z < a < z


3 6= 3 (character digits 6= integer digits)

Array of Pointers
CS1010E Lecture 10 p.2/33

CS1010E Lecture 10 p.4/33

Using Characters

Character Array

Declaration (Single Variable/Array)


Uninitialized:
char ch, chArray[10];
Initialized:
char c=d;

Using an array as a lookup-table.

char vowels[5]={a,e,i,o,u};

Output
printf("The character is : %c\n", c);

E H

N R

10 11

12 13

int main(void)
{
int num;
char c, chk[14]={#,B,A,E,H,
J,L,M,N,R,
U,W,X,Y};

Input

scanf("%d", &num); // input matric no.


c = chk[13 - sumDigits(num)%13];
printf("Check letter: %c\n", c);
return 0;

scanf("%c", &ch);
}
CS1010E Lecture 10 p.5/33

Reading Characters

CS1010E Lecture 10 p.7/33

Character Strings
A character array is defined as an array in
which the individual elements are stored as
characters.

int main(void)
{
char ch;
// Repeatedly reads uppercase characters
scanf("%c", &ch);
while (ch >= A && ch <= Z)
{
ch = (ch - A) + a;
printf("lowercase: %c\n", ch);
scanf("%c", &ch);
}
return 0;

A characters string is a character array


consisting of a sequence of characters
terminated with a null character \0.
The null character need not be the last
element of the character array, and may occur
earlier.
The null character has an ASCII integer
equivalent of zero, so 0 is equal to 0.

Will the above work?


CS1010E Lecture 10 p.6/33

CS1010E Lecture 10 p.8/33

Character Strings

Reading a Word

Character string constants are enclosed in double


quotes, as in "input.txt", "r", and "15762".

To read a string as a word (i.e ignoring all whitespaces,


just like in %d and %lf), use %s.
char filename[40];

A character string array can be initialized using string


constants
char filename[10]="input.txt";

printf("Enter file name: ");


scanf("%s", filename);

or using character constants.

In the above program, the user must ensure that the


filename is no longer than 39 characters since scanf
automatically appends a null character at the end.

char filename[10]={i,n,p,u,t,
.,t,x,t,\0};

To store a string that has n characters, the character


string array must have a size of at least n + 1 to store
the null character \0.

Note the absence of the & operator in the second


argument of scanf as filename is already an
address to the first element of the array.

CS1010E Lecture 10 p.9/33

CS1010E Lecture 10 p.11/33

Character Strings

Reading Character as a Word

Since an array cannot be assigned, and a string is a


special form of a character array, strings cannot be
assigned directly.

int main(void)
{
char word[2];

scanf("%s", word);
while (word[0] >= A && word[0] <= Z)
{
word[0] = (word[0] - A) + a;
printf("lowercase: %c\n", word[0]);

The following are not correct!


char file1[10], file2[10]="input.txt";
file1 = "input.txt";
file1 = file2;

// One character then \0

// invalid
// invalid

scanf("%s", word);

To print a character string, use the %s format specifier


with the printf function:
printf("File name: %s\n", filename);

}
return 0;
}

Prints until the first occurrence of \0.


CS1010E Lecture 10 p.10/33

CS1010E Lecture 10 p.12/33

Reading a Sentence

String Functions

To read an entire sentence (including spaces) from the


keyboard until <enter> is pressed and store it as a
single string, we use the following template.
char str[101];
printf("Enter sentence: ");
fgets(str, 101, stdin);
if (str[strlen(str)-1] == \n)
str[strlen(str)-1] = \0;

Suppose s and t are strings.


strlen(s)

Returns the length of the string s.


strcmp(s,t)

Compares each s[i] and t[i], i = 0, 1, 2, . . .


A negative value is returned if there exists a
s[i]<t[i] with s[j ]=t[j ], j < i

Reads up to 100 characters.


stdin refers to standard input; to read an entire
line from a file, replace stdin with the name of the
FILE * pointer.
fgets stores \n if less than 100 characters.

A positive value is returned if there exists a


s[i]>t[i] with s[j ]=t[j ], j < i
zero is returned if s[i]=t[i], i < k and
s[k ]=t[k ]=\0.

CS1010E Lecture 10 p.13/33

String Functions

CS1010E Lecture 10 p.15/33

String Functions

The Standard C library contains a number of functions


for working with strings.

strcpy(s,t)

Usage of these functions require that you include


<string.h>.

strcat(s,t)

All string functions (as well as printf using %s) work


on the basis of the null character.

strcpy/strcat returns pointer to the result string, e.g.


char *strcat(char *str1, const char *str2);

In the next slide, assume that s and t are character


strings.

This is to allow string functions to be composed:

Be mindful of the amount of space required when


declaring s and t.

CS1010E Lecture 10 p.14/33

Copies string t to string s.

Concatenates (joins) string t to the end of string s.

char str1[10]="abc", str2[10]="bcd";


int len = strlen(strcat(str1,str2));

fyi: const keyword prevents the string str2 from


being modified.
CS1010E Lecture 10 p.16/33

Looping a String

etslay eakspay igpay atinlay

There are generally two ways to loop through all


characters of string s.
int i;
i = 0;
while (s[i] != \0)
{
// access s[i]
i++;
}

To convert an English word to Pig Latin,


1. Find the first vowel in the word.
2. The sub-string beginning at the start till just before
the first vowel is moved to the end of the word.

int len, i;
len = strlen(s);
for (i = 0; i < len; i++)
{
// access s[i]
}

3. Add "ay" at the end of the word.


The phrase lets speak pig latin is thus converted to
etslay eakspay igpay atinlay.
Problem solving strategies:

Note that the return type of strlen is unsigned int,


so always perform the assignment len = strlen(s)
to convert to int type before proceeding.

Linear search for the first vowel;


Copy and concatenate strings;
Use \0 to terminate sub-string.

CS1010E Lecture 10 p.17/33

CS1010E Lecture 10 p.19/33

Pointers in Strings

etslay eakspay igpay atinlay

Using pointers in strings allow us to specify a


substring of the string.
Consider the following code:
char str1[40] = "politics", str2[40],
*ptr;
ptr = &str1[4
strcpy(str2,ptr);
*ptr = \0;
printf("%s %s\n", str1, str2);

int isVowel(char c)
{
return (c==a || c==e ||
c==i || c==o || c==u);
}
// pig stores the piglatin of str
void piggy(char *str, char *pig)
{
char *v;
v = str;
while (*v != \0 && !isVowel(*v))
v++;
strcpy(pig,v);
*v = \0;
strcat(strcat(pig,str),"ay");

What is the output?

return;
}
CS1010E Lecture 10 p.18/33

CS1010E Lecture 10 p.20/33

etslay eakspay igpay atinlay

Two-Dimensional Arrays

The following main function reads strings until a


standalone "." is encountered.
int main(void)
{
char str[40], pig[40];
scanf("%s", str);
while (strcmp(str,".") != 0)
{
piggy(str,pig);
printf("%s ", pig);
scanf("%s", str);
}
printf("\n");
return 0;
}

What happens to str after the piggy function call?

In C, a grid or table of data is represented


with a two-dimensional array.

CS1010E Lecture 10 p.21/33

Two-Dimensional Arrays

CS1010E Lecture 10 p.23/33

Two-Dimensional Arrays

A set of data values that is visualized as a


row or column is easily represented by a
one-dimensional array.

Each element in a two-dimensional array is


referenced using an identifier followed by row
and column subscripts.

However, there are many examples in which


the best way to visualize a set of data is with
a grid or a table of data, which has both rows
and columns.

Each subscript value begins with 0 and has


its own set of brackets.
In the previous array, the identifier is x; the
value in position x[2][1] is 6.

A two-dimensional array with four rows and


three columns is shown in the next slide.

Common errors: x(2)(3), x[2,3] or


x(2,3).
Visualize a 2D array as a 1D array, where
each element is a separate 1D array.

CS1010E Lecture 10 p.22/33

CS1010E Lecture 10 p.24/33

Two-Dimensional Arrays

Declaration and Initialization


A two-dimensional array can be initialized with a
declaration statement.
int x[4][3]={{ 2, 3,-1},
{ 0,-3, 5},
{ 2, 6, 3},
{-2,10, 4}};

and x[i] are symbolic addresses to the first


element of their respective arrays.
x

As they cannot be assigned, the following is


incorrect.
x[0] = x[1];

// invalid

If the initializing sequence is shorter than the array, the


rest of the values are set to zero.
Zero entire array: int x[4][3]={{0}};
Initializer lists used only during declaration; x and
x[i] cannot be assigned.

CS1010E Lecture 10 p.25/33

Declaration and Initialization


To define a two-dimensional array, we specify the
number of rows and the number of columns in the
declaration statement.
Assuming row-major ordering, the row number is
written first as the primary dimension.
Both the row number and the column number are in
brackets, as shown in this statement:
int x[4][3];
In the above, x has a primary dimension (row) of 4,
and secondary dimension (column) of 3.

CS1010E Lecture 10 p.26/33

CS1010E Lecture 10 p.27/33

Accessing 2D Array Elements


Two nested for loops needed to access all elements.
int i, j, table[5][4];
for (i = 0; i < 5; i++)
for (j = 0; j < 4; j++)
t[i][j] = i;

Input into a 2D array element-by-element.


for (i = 0; i < 5; i++)
for (j = 0; j < 4; j++)
scanf("%d", &(table[i][j]));

Printing a 2D array in table form.


for (i = 0; i < 5; i++)
{
for (j = 0; j < 4; j++)
printf("%d ", table[i][j]);
printf("\n");
}
CS1010E Lecture 10 p.28/33

Function Arguments

Array of Pointers

When a 2D array is used as a function argument, the


address is passed together with the number of rows
and columns to process.
void print1DArray(int list[], int numElem)
{
int i;
for (i = 0; i < numElem; i++)
printf("%d ", list[i]);
printf("\n");
return;
}

The symbolic address of a 1D array can be stored


using an integer pointer. It follows that each row of a
2D array can be stored using an array of pointers.
int table[4][3]={{ 2, 3,-1},{ 0,-3, 5},
{ 2, 6, 3},{-2,10, 4}};
int *x[4], i, j;
for (i = 0; i < 4; i++)
x[i] = table[i];

void print2DArray(int table[][4], int rows, int cols


{
int i;
for (i = 0; i < rows; i++)
print1DArray(table[i], cols);
return;
}
CS1010E Lecture 10 p.29/33

CS1010E Lecture 10 p.31/33

Function Arguments

Array of Pointers

Each row of a 2D array may be simply passed to a


function that receives a 1D array.
Just as int list[] is int *list,
int table[][4] is int (*table)[4], i.e. a
pointer to an array of 4 integers.
Secondary size in int table[][4] is mandatory;
table+1 refers to 4 elements after the current
location, or the next row.
As each row of a 2D array is allocated consecutively in
memory, table[i][j] is equivalent to
*(*(table + i) + j).
CS1010E Lecture 10 p.30/33

Passing an array of pointers into a function.


void sort(int *x[], int n)
{
int i, j, minIndex, *temp;
for (i = 0; i < n-1; i++)
{
minIndex = i;
for (j = i+1; j < n; j++)
if (*(x[j]) < *(x[minIndex]))
minIndex = j;
temp = x[minIndex]; x[minIndex] = x[i]; x[i] = temp;
}
return;
}

What is the output of the following?


sort(x,4);
for (i = 0; i < 4; i++)
{
for (j = 0; j < 3; j++)
printf("%d ",x[i][j]);
printf("\n");
}
CS1010E Lecture 10 p.32/33

Lecture Summary
Characters and Strings
Understanding ordering of characters to perform
desired conversions.
Strings are character arrays with a \0 character.
Operation of string functions are dependent on the
position of the null character.
Two-Dimensional Arrays.
Nested loop to access array elements.
Passing 2D arrays into functions via pointer
parameters.
Array of Pointers.
CS1010E Lecture 10 p.33/33

Das könnte Ihnen auch gefallen