Arrays II (Strings)

1 / 32

# Arrays II (Strings) - PowerPoint PPT Presentation

Arrays II (Strings). Data types in C. Integer : int i; Double: double x; Float: float y; Character: char ch; char cha[10], chb[]={‘h’,’e’,’l’,’l’,’o’}; Ex. scanf(“%c”, &amp;ch); Ex. ch = ‘A’; Ex. for (i=0;i&lt;5; i++) printf(“%c”, chb[i]);. Strings.

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.

## PowerPoint Slideshow about 'Arrays II (Strings)' - suchi

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
Arrays II

(Strings)

Data types in C
• Integer : int i;
• Double: double x;
• Float: float y;
• Character:
• char ch;
• char cha[10], chb[]={‘h’,’e’,’l’,’l’,’o’};
• Ex. scanf(“%c”, &ch);
• Ex. ch = ‘A’;
• Ex. for (i=0;i<5; i++) printf(“%c”, chb[i]);
Strings
• There is no string type in C. Instead, to approximate strings, we will use arrays of characters.
• To transform a simple array of characters into a string, it must contain the '\0' character in the last cell.
• A string is an array of characters with the last character of the array as the “null” character in C language
• char chs[]={‘h’,’e’,’l’,’l’,’o’,’\0’};
• printf(“%s”, chs);
Strings
• Note that '\0' is one character. It is called the null character or the end-of-string character.
• char chs[]={‘h’,’e’,’l’,’l’,’o’,’\0’};
• printf(“%s”, chs);
• Compare with the previous example:
• char cha[]={‘h’,’e’,’l’,’l’,’o’};
• for (i=0;i<5; i++) printf(“%c”, cha[i]);
Strings
• To declare a string and initialize it we could do it the same way as before, but add ‘\0’ at the end:
• char city[ ] = {'T', 'o', 'r', 'o', 'n', 't', 'o'};
• char city[ ] = {'T', 'o', 'r', 'o', 'n', 't', 'o', '\0'};
• But there is a simpler way:
• char city[ ] = “Toronto”;
• The result is exactly the same. By using the simpler way, the '\0' is added automatically at the end.

0 1 2 3 4 5 6 7

'T'

'o'

'r'

'o'

'n'

't'

'o'

'\0'

city

“X” and 'X'
• Double quotes “ “ represent a string, A single quote ' ', one character.
• '?' is the single character ? But “?” is an array size 2 containing the '?' character and the '\0' character.
• A string constant can be represented in double quotes (remember “This is my first C program.” ?).
First C program
• A simple C program

#include <stdio.h>

int main()

{

printf(“This is my first program”);

return 0;

}

Filling a string
• We have already seen how to fill a string by initializing it in a declarative statement. Now how to do it in an executable statement.

char city[30];

• To fill a string from standard input (scanf), we use a special placeholder for strings %s.
• scanf (“%s”, city);

(Notice the absence of &. It is not necessary here since city is already a pointer)

Exercise
• Write a C program that will ask user to input the last name and first name. Print the names (both first and last name) on the screen using strings.
Arrays of strings
• It is also possible to have arrays of strings. Since strings are themselves arrays, then we need to add a second size. An array of strings is in fact an array with two dimensions, width (columns) and height (rows).

‘O'

'T'

‘H'

‘o'

‘a'

‘t'

‘l'

‘t'

‘r'

‘i'

‘a'

‘o'

‘f'

‘w'

‘n'

‘a'

‘a'

‘t'

‘o'

‘\0'

‘x'

‘\0'

‘\0'

Array of strings

char city[3][10];

0 1 2 3 4 5 6 7

city

Array of strings
• char list_cities[100][15]; will be able to contain 100 city names with a maximum of 14 letters per city. Why not 15?
Arrays of strings (cont.)
• Example: An array containing the names of the months.
• char months [12][10] = {“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”};
Filling a string
• There is one problem with the %s placeholder when used with scanf (or fscanf). It considers the space as a delimiter. Therefore, if for a city name you enter Los Angeles, you will get only Los stored in the string.
• The solution is to use a function from the string library (string.h) called gets (or fgets if you read from a file). That function only considers the “enter” key as delimiter not the space. Instead of scanf (“%s”, city); you use gets (city); Instead of fscanf (in, ”%s”, city); you use fgets(city, size, in);
Printing a string
• The space problem does not occur with printf. If the city is “Los Angeles” then a printf (“%s”, city); will print out the entire city name.
• There is a puts function in the string library as an alternative to printf but its use is less imperative than the gets.
Exercise
• Write a C program that will contain an array to store 2/3 strings. Let the user input the three strings and print out the three strings on the screen.
• The Three strings will be the last name of your group members
• you need to do this exercise with a group of 2/3 people
String Constant Macros
• A string can also be a constant macro like:
• #define ERROR “Sorry – Invalid Operation”
• #define STRING “This is a string constant”
• #define PI 3.14
String functions
• We just learned about gets, but there are many more useful functions in the string.h library.
• strcat: the string concatenation function. strcat needs two arguments (two strings) and then adds up the two strings:

char s1[ ] = “The quick “;

char s2[ ] = “brown fox.”;

strcat (s1, s2);

printf (“New string is: %s”, s1);

/* notice that the new string is placed in the first argument */

New string is: The quick brown fox.

String functions
• strncat: the same thing as strcat except that it has a third argument specifying how many characters to the second string to append:

char s1[ ] = “The quick “;

char s2[ ] = “brown fox.”;

strncat (s1, s2, 3);

printf (“New string is: %s”, s1);

/* notice that the new string is placed in the first argument */

New string is: The quick bro

String functions
• strcmp: this function performs a string comparison between two strings. It uses the ASCII code to compare. It starts with the first character and then continues character by character. When characters are all identical, the longer string is the greater one. It returns 0 if the two strings are identical, a negative number if the first string is smaller than the second and a positive number when the first string is larger than the second.

char city1[ ] = “Toronto”;

char city2[ ] = “Vancouver”;

if (strcmp(city1, city2) < 0)

/* condition is true here because “T” is smaller than “V” /*

String functions
• strncmp: identical to strcmp except that a third argument specifies how many characters to compare.

char city1[ ] = “Mexicali”;

char city2[ ] = “Mexico City”;

if (strcmp(city1, city2) < 0)

/* condition is true here because “a” is smaller than “o” /*

if (strncmp(city1, city2, 4) < 0)

/* condition is false here, the answer would be 0 because the first 4 characters are identical /*

String functions
• strcpy: the function to transfer a string into a variable. Equivalent to the assignation operator. With strings you cannot do city=”Toronto”; in an executable statement. To do an assignment we use strcpy.

char city[10], city2[10];

strcpy (city, “Toronto”);

/* places “Toronto” into city /*

strcpy (city2, city);

/* places “Toronto” into city2 /*

0 1 2 3 4 5 6 7 8 9

city

'T'

'o'

'r'

'o'

'n'

't'

'o'

'\0'

?

?

String functions
• strncpy: strncpy is like strcpy except for a third argument specifying how many characters to copy.

char city[10], city2[10];

strcpy (city, “Toronto”);

/* places “Toronto” into city /*

strncpy (city2, city, 4);

/* places “Toro” into city2 /*

0 1 2 3 4 5 6 7 8 9

city2

'T'

'o'

'r'

'o'

'\0'

?

?

?

?

?

String functions
• strlen: the strlen function returns the length of the string not counting the null character.

char city[10];

strcpy (city, “Toronto”);

/* places “Toronto” into city */

printf (“%d”, strlen (city));

/* displays 7 on the screen */

Exercise
• Write a C program that will able to compare two strings and print out the larger string.
Passing a string to a function
• Passing a string to a function is the same thing as passing an array of numerals. We pass only the pointer to its first cell.
• Here is a function that takes in a string a counts the number of vowels (a,e,i,o,u) in it.
• Notice that contrary to numerical arrays, we don't need to pass the size because for strings it is easy to determine its size from inside the function (which is not possible for arrays of numerals).
Passing a string to a function

int

count_vowels (char string[])

{

int nv=0, i;

for (i=0; i<strlen(string); ++i)

if (string[i]=='a'||string[i]=='e'||string[i]=='i'||string[i]=='o'||string[i]=='u')

nv = nv + 1;

return (nv);

}

Passing a string to a function

The main program would look like this:

int main (void)

{

char s[100];

int vowels;

printf ("Enter a sentence: ");

gets (s);

vowels = count_vowels (s);

printf ("Thre sentence contains %d vowels.\n", vowels);

return (0);

}

Character functions
• Functions from the string.h library work one entire string at a time. Character functions, present in the ctype.h library work one character at a time only.
• Here is a list of the character functions:
• isalpha returns true if the character is in the range of A-Z or a-z.
• isalnum returns true if the character is in the range of A-Z or a-z or 0-9.
• isdigit returns true if the character is in the range of 0-9.
Character functions
• isspace returns true if the character is a space.
• ispunct returns true if the character is a punctuation character.
• islower returns true if the character is in the range of a-z.
• isupper returns true if the character is in the range of A-Z.
Character functions
• tolower transforms the letter into a lowercase letter.
• toupper transforms the letter into an uppercase letter.