26
Character Arrays (Single- Dimensional Arrays) A char data type is needed to hold a single character . To store a string we have to use a single- dimensional array of characters. The array of characters stores each character’s ASCII code. Every character has an associated ASCII code (American Standard Code for Information Interchange). The code ranges from 0 - 255 for upper-case letters, lower-case

Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional

Embed Size (px)

Citation preview

Page 1: Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional

Character Arrays (Single-Dimensional Arrays)

A char data type is needed to hold a single character. To store a string we have to use a single-dimensional array of characters. The array of characters stores each character’s ASCII code. Every character has an associated ASCII code (American Standard Code for Information Interchange). The code ranges from 0 - 255 for upper-case letters, lower-case letters, numeric digits, punctuation marks and other symbols.

Page 2: Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional

Declaring a String

A string is an array of characters. For example: To hold a string of 10 characters you need to declare an array of type char with 11 elements.

char S[11];

But why 11 and not 10. This is so the 11th position is reserved for the string terminator which is referred by ‘\0’. The string terminator ‘\0’ is also called the null character.

Page 3: Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional

Initializing the string

The string is initialized with character constants. For example: If we want to initialize digits 1 to 9 in a string S, it can be done in the following manner.

char S[10] = {‘1’,’2’,’3’,’4’,’5’,’6’,’7’,’8’,’9’,’\0’};

But it is convenient to use a literal string. A literal string is one enclosed in double quotes.

S[10] = {“123456789}. In this case a null terminator character is not required as the system puts it itself

Page 4: Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional

We can also initialise in the following mannerchar S[3];S[0] = ‘A’;S[1] = ‘B’;S[2] = ‘\0’;

In this it is the user’s responsibility to put the terminator character

Page 5: Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional

Accessing Elements in an Array

The elements of the string can be acccessed using a for loop.

for(i=0; S[i] != ‘\0’; i++)

{

printf(“The elements %d is %c”,S[i],S[i]);

}

The condition in the for loop says loop until it reaches the terminator or null character which signifies the actual end of string. Why do I use the word “actual”? As the string can be declared of a

Page 6: Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional

size “20” but can contain only 7 characters and the 8th character to be a null character. For example:

char S[20] = “Jamaica”;int i;for(i=0; S[i] != ‘\0’; i++){

printf(“%c”, S[I]);}

Here it is not ideal to have the size as condition . It is often good programming practice to have the condition of null character in a for loop. When accessing character array elements.

Page 7: Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional

Inputting using scanfThe scanf requires a modifier %s to accept a string. For example

char S[5];scanf(“%s”,S);

Here & is not required as S has address of the first element of the character array.

S =

A scanf requires you to specify the address to

4001 4002 4003 4004 4005

4001

Page 8: Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional

to accept as input. Since S already has the address stored it does not require &.

The scanf accepts the input from the first non-white-space character encountered to the next white-space character (space, tab or newline). It does not include the white-space characters.

Multiple string can be entered using scan like:

scanf(“%s %s %s”,S,S1,S2);

If you enter less number of strings than expected by scanf it will continue to look for remaining strings until you enter it.

Page 9: Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional

Inputting using gets():

The gets() accepts string from keyboard. The gets() reads all characters entered up to the first newline character encountered as opposed to scanf which stops when it encounters any whitespace line tab or space.

The syntax is:

gets(string name);

Page 10: Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional

Printing Strings

The string can be printed using a printf or puts. In the case of printf it needs the format specifier %s. For example:

printf(“%s”,S);

In the case of puts the syntax is:puts(string variable/literal string);Example: puts(S);

puts(“Welcome”);puts(“ “);puts(“\n”);

Page 11: Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional

Character Test Functions

isalnum() Returns true if character is a letter or digit

isalpha() Returns true if character is a letter.

isascii() Returns true if character is a standard ASCII character (between 0 - 127)

isdigit() Returns true if character is a digit

islower() Returns true of character is a lowercase character

isupper() Returns true if character is a uppercase character

ispunct() Returns true is character is a punctuation character

Page 12: Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional

isspace() Returns true is character is a white space character. This includes tab, space, carriage return

isxdigit() Return true if character is a hexadecimal digit (0-9, a - f, A -F)

Note

The header “ctype.h” contains the above functions so include this header file.

Page 13: Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional

Miscellaneous Character functions

toupper Converts from lowercase to uppercase

tolower() Converts from upper-case to lower-case

Note: All the character functions are defined in the header file “ctype.h”. To use these functions, you need to use this header file.

Page 14: Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional

Passing Strings to functions

A string is a character array, so it should be passed in in a similar manner as integer arrays.

It should in the prototype in the following syntaxes:

data type function-name(char arrayname[]);

data type function-name(char *arrayname);

data type function-name(char arrayname[size of array]);

It should be specified in the calling function as:

functionName(arrayname);

Page 15: Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional

It should be specified in the function definition or description as:

data type functionName(char arrayname[]){}

data type functionName(char arrayname[size of the array]){}

Page 16: Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional

Example Problem of Strings in Functions:

#include<stdio.h>

#include<ctype.h>

void evalLetter_Digit(char S[]);

void main()

{

char S[20];

do

{

printf(“\nPlease enter the string without any special characters:”);

gets(S);

}while(!isalnum(c))

Page 17: Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional

evalLetter_Digit(char S[])

{

int i, alpha,digit = 0;

for(i=0; S[i] != ‘\0’; i++)

{

if(isalpha (S[i])

alpha++

else

if(isdigit (S[i])

digit++;

}

Page 18: Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional

Printf(“\n\n The number of letters in the string %s is %d”, s, alpha);

printf(“\n\n The numbr of digits in the string %s is : %d”,s,digit);

}

Page 19: Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional

Accepting Keyboard Input

Most C programs require some form of input from the keyboard (that is, from stdin).

Character input

The character input functions reads input from a stream one character at a time. When called, each of these functions returns the next character in the stream, or EOF if the end of the file has been reached or an error has occurred. EOF is a symbolic constant defined in stdio.h as –1. Character input functions differ in terms of buffering and echoing

Page 20: Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional

Some character input functions are buffered. This means that the operating system holds all characters in a temporary storage space until you press Enter, and then the system sends the characters to the stdin stream. Others are unbuffered, meaning that each character is sent to stdin as soon as the key is pressed.

Some input functions automatically echo each character to stdout as it is received. Others don’t echo; the character is sent to stdin and not stdout. Because stdout is assigned to the screen, that’s where input is echoed.

Page 21: Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional

The getchar() FunctionThe function getchar() obtains the next character from the stream stdin. It provides buffered character input with echo. The use of getchar is demonstrated below. Notice that the putchar() function simply displays a single character onscreen.

1. #include<stdio.h>

2. void main()

3. { int ch = 0;

4. while (ch != '\n')

5. {

6. ch = getchar();

7. putchar(ch);

8. }

9. }

Page 22: Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional

On line 4, the getchar()function is called and waits to receive a character from stdin. Because getchar is a buffered input function, no characters are received until you press Enter. However each key you press is echoed immediately on the screen.

When you press Enter, all the characters you entered, including the newline, are sent to stdin by the operating system. The getchar() function returns the characters one at a time, assigning each in turn to ch.

Each character is compared to the newline character ‘\n’ and, if not equal, displayed onscreen with putchar(). When a newline is returned by getchar(), the while loop terminates.

The getchar() function can be used to input entire lines of text, as shown in the previous example. However, other input functions are better suited for this task.

Page 23: Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional

The getch() Function

The getch() function obtains the next character from the stream stdin. It provides unbuffered character input without echo. The getch() functon isn’t part of the ANSI standard, meaning it amy not be available on every system. The header file foor this function is conio.h.

Because it is unbuffered, getch() returns each character as soon as the key is pressed, without waiting for the user to press Enter. Because getch() doesn’t echo its output, the characters aren’t displayed onscreen. getch() may be used as follows:

Page 24: Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional

#include<stdio.h>

#include<conio.h>

void main()

{

int ch;

while (ch != ‘\r')

{

ch = getch();

putchar(ch);

}

}

Page 25: Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional

When this program runs, getch() returns each character as soon as you press a key - it doesn’t wait for you to press Enter. There is no echo, so the only reason that each character is displayed onscreen is the call to putchar(). To understand this better remove the line with putchar(ch) and run the program. When you rerun the program you will find that nothing you type is echoed to the screen.

Page 26: Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional

The getche() Function

The getche() function is exactly like getch(), except that it echoes each character to stdout. When the program runs, each key you press is displayed onscreen twice – once as echoed by getche(), and once as echoed by putchar(). getche() is not an ANSI-standard comand, but many C compilers support it.