Sunteți pe pagina 1din 8

11-1 String Concepts

Chapter 11
Strings In general, a string is a series of characters treated as
a unit. Computer science has long recognized the
Objectives
❏ To understand design concepts for fixed-length and variable-
importance of strings, but it has not adapted a
standard for their implementation. We find, therefore,
❏ To understand the design implementation for C-language
length strings
that a string created in Pascal differs from a string
created in C.
❏ To write programs that read, write, and manipulate strings
delimited strings

❏ To write programs that use the string functions


❏ To write programs that use arrays of strings Topics discussed in this section:
Fixed-Length Strings
Variable-Length Strings

Computer Science: A Structured Programming Approach Using C 1 Computer Science: A Structured Programming Approach Using C 2

Note 11-2 C Strings


C uses variable-length,
delimited strings.
A C string is a variable-
variable-length array of characters that
is delimited by the null character ‘\0’.

Topics discussed in this section:


Storing Strings
The String Delimiter
String Literals
Strings and Characters
Declaring Strings
The end-of-string null character ( \0 )
is used to detect end of the string
Initializing Strings
Strings and the Assignment Operator
FIGURE 11-1 String Taxonomy FIGURE 11-2 String Formats Reading and Writing Strings
Computer Science: A Structured Programming Approach Using C 3 Computer Science: A Structured Programming Approach Using C 4

1
character literal – a single character in single
Differences Between Strings and Character Arrays
quotes ‘ ’

string literal – sequence of characters enclosed


in double quotes “ ”

FIGURE 11-3 Storing Strings FIGURE 11-4 Storing Strings and Characters FIGURE 11-8 String Literal References

Computer Science: A Structured Programming Approach Using C 5 Computer Science: A Structured Programming Approach Using C 6

Note
Memory for strings must be allocated before the
string can be used.
Declaration of String
 Example:
char symbol; // declare a character
char str[80]; // declare a string

 Example
#define NUM_STUDENTS 30 //defined constants
#define NAME_LEN 25 //defined constants
Initializing Strings

char names [NUM_STUDENTS] [NAME_LEN];

FIGURE 11-9 Defining Strings

Computer Science: A Structured Programming Approach Using C 7 Computer Science: A Structured Programming Approach Using C 8

2
Initialization of a String Sample program:
#include <stdio.h>
int main()
{
 To assign value into the string or character int i, size;
char name[10][20];
 Example:
printf("How many names do you plan to input?(max is 10): ");
char message[81]; //declare scanf("%d", &size);
How many names do you plan
printf("Enter names:\n"); to input?(max is 10): 3
for(i=0; i<size; i++)
message[] = “Shah”; //assign value scanf("%s", &name[i]);
Enter names:
razin
mahmud
OR habibah
printf("\nThese are the names:\n");
message[81] = “Shah”; for(i=0; i<size; i++)
These are the names:
printf("%s\n", name[i]); razin
OR mahmud
return 0; habibah
message[81] ={‘S’,‘h’,‘a’,‘h’}; } Press any key to continue

Computer Science: A Structured Programming Approach Using C 9 Computer Science: A Structured Programming Approach Using C 10

11-3 String Input/Output Functions String Formatting using printf


To get input string: #include <stdio.h>
scanf ( ) int main()
fgets( ) {
gets( ) char sentence[20]="Be happy today";
getchar ( )
getch ( ) printf("| %-20s |\n", sentence); //Displays left-justified in a field of 20 char
To produce string output: printf("| %20s |\n", sentence); //Displays right-justified in a field of 20 char
printf ( ) return 0;
fputs() }
puts( )
putchar ( ) | Be happy today |
| Be happy today |
Topics discussed in this section: Press any key to continue

Formatted String Input/Output


String Input/Output
Computer Science: A Structured Programming Approach Using C 11 Computer Science: A Structured Programming Approach Using C 12

3
Example:Read Student Names and Scores

#include <stdio.h>
int main()
{
char first[80]="Abdul Halim";
char last[80]="Abdul Razak";
int score=88;

printf("%s %s %d\n", first, last, score);

return 0;
}

Abdul Halim Abdul Razak 88


Press any key to continue
FIGURE 11-11 gets and fgets Functions

Computer Science: A Structured Programming Approach Using C 13 Computer Science: A Structured Programming Approach Using C 14

Demonstrate gets Operation PROGRAM 11-5 Demonstrate fgets Operation


#include <stdio.h> #include <stdio.h>
int main() int main()
{ {
char str[80]; char str[80];

printf("Please enter a string: "); printf("Please enter a string: ");


gets(str); fgets(str, sizeof(str), stdin);

printf("Here is your string: %s", str); printf("Here is your string: %s", str);
return 0; return 0;
} }
Please enter a string: How are you? Please enter a string: How are you?
Here is your string 1: How are you?Press any key to continue Here is your string: How are you?
Press any key to continue

Computer Science: A Structured Programming Approach Using C 15 Computer Science: A Structured Programming Approach Using C 16

4
Demonstrate puts Operation
#include <stdio.h>
int main()
{
char str[80]="How are you?";

puts(str);
puts(str+5);

return 0;
}

How are you?


re you?
Press any key to continue

FIGURE 11-12 puts and fputs Operations

Computer Science: A Structured Programming Approach Using C 17 Computer Science: A Structured Programming Approach Using C 18

Demonstrate fputs Operation


#include <stdio.h> getchar(), getch(), putchar()
int main()
#include <stdio.h>
{ int main()
 getchar {
char str[80]="How are you?"; char c;
 to input a single character printf("Please type ONE character : ");
c=getchar();
fputs(str, stdout);  requires you to hit enter. printf("You typed : %c\n", c);
return 0;
fputs(str + 5, stdout); }
return 0;  getch #include <stdio.h>
} #include <conio.h>
 to input a single character int main()
{
How are you?re you?Press any key to continue  reads a key hit without char c;
waiting for you to press printf("Please type 1 character : ");
c=getch();
enter. printf("You typed : %c\n", c);
return 0;
}

 putchar #include <stdio.h>


int main()
 outputs characters {
char letter;
individually for (letter='A'; letter<='Z'; letter++)
putchar (letter);
printf("\n");
return 0;
Computer Science: A Structured Programming Approach Using C 19 Computer Science: A Structured Programming Approach Using C } 20

5
PROGRAM 11-8 Print Selected Sentences PROGRAM 11-10 Array of string: Print Days of the Week
//Echo keyboard input that begins with capital letter. Consider, for example, the need to store the days of the week in their textual format.
#include <stdio.h> We could create a two-
two-dimensional array of seven days by ten characters.
#include <ctype.h> #include <stdio.h>
int main() int main()
{ {
char str[80]; int i;
char days[7][10]={"Sunday","Monday","Tuesday",
while(fgets(str, sizeof(str), stdin)) "Wednesday","Thursday","Friday",
if(isupper(str[0])) "Saturday"};
fputs(str, stdout);
printf("The days of the week\n");
return 0;
} The days of the week
for(i=0; i<7; i++) Sunday
Now is the time puts(days[i]); Monday
Now is the time Tuesday
for all good students return 0; Wednesday
to come to the aid } Thursday
of their school. Friday
Amen Saturday
Amen Press any key to continue
Computer Science: A Structured Programming Approach Using C 21 Computer Science: A Structured Programming Approach Using C 22

11-5 String Manipulation String Library Functions (string.h)


Functions
Because a string is not a standard type, we cannot use  strcat (string1, string2)
it directly with most C operators. Fortunately, C  concatenate string2 to string1
provides a set of functions to manipulates strings.
 strcmp (string1, string2)
Topics discussed in this section:  compare string1 to string2

String Length and String Copy  strcpy (string1, string2)


String Compare and String Concatenate
 Make string1 equal to string2
Additional library functions
(isalpha, isdigit, islower, isupper, tolower, toupper)  strlen (string)
 Determine length of string

Computer Science: A Structured Programming Approach Using C 23 Computer Science: A Structured Programming Approach Using C 24

6
Sample of String Functions (strcat) Sample of String Functions (strcpy, strlen)
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
int main() int main()
{ {
char word1[12]="alpha“, word2[12]="beta"; char word1[12]="alpha“, word2[12]="beta";
strcat(word1,word2); int length;
Word 1 is: alphabeta strcpy(word1,word2); Word 1 is: beta
printf("Word 1 is: %s\n", word1); Word 2 is: beta Word 2 is: beta
printf("Word 2 is: %s\n", word2); Press any key to continue printf("Word 1 is: %s\n", word1); Length of Word 1 is: 4
printf("Word 2 is: %s\n", word2); Press any key to continue
return 0; length=strlen(word1);
} printf("Length of Word 1 is: %d\n", length);

return 0;
word1 word2 strcat(word1,word2) }

“alpha” “beta” word1 = “alphabeta” word1 word2 strcpy(word1,word2)


word2 = “beta” “alpha” “beta” word1 = “beta”
word2 = “beta”
Computer Science: A Structured Programming Approach Using C 25 Computer Science: A Structured Programming Approach Using C 26

Sample of String Functions (strcmp)


#include <stdio.h>
#include <string.h>
int main()
{
char word1[12]="alpha", word2[12]="alpha",
word3[12]="beta", word4[12]="alien";

int num1=strcmp(word1,word2);
int num2=strcmp(word1,word3);
int num3=strcmp(word1,word4);

printf("%d\n", num1);
printf("%d\n", num2);
printf("%d\n", num3);
0
return 0;
-1
}
1
Press any key to continue FIGURE 11-17 String Compares

Computer Science: A Structured Programming Approach Using C 27 Computer Science: A Structured Programming Approach Using C 28

7
#include <stdio.h>
#include <string.h>
int main()
{
Example of strcmp( ) usage
String Library Functions (ctype.h)
char name[3][10];
char temp[10];
int i, j;
 isalpha
printf("Enter 3 names:\n");
for (i=0; i<3; i++)  returns true if the character is in the range of A-Z or a-z.
scanf("%s", &name[i]);  isdigit
for (i=3; i>=0; i--) //bubble sort algorithm
 returns true if the character is in the range of 0-9.
{  islower
for(j=1; j<=i; j++){
if (strcmp(name[j-1], name[j])>0){  returns true if the character is in the range of a-z.
strcpy(temp, name[j-1]);  isupper
strcpy(name[j-1], name[j]);
strcpy(name[j], temp);  returns true if the character is in the range of A-Z.
}
Enter 3 names:
 tolower
}
} bakri  if isupper is true, return the lowercase character otherwise return the
ali character.
abdul
printf("Names in alphabetic order:\n");
Names in alphabetic order:  toupper
for (i=0; i<3; i++)
printf("%s\n", name[i]); abdul  if islower is true, return the uppercase character otherwise return the
ali character.
return 0; bakri
} Press any key to continue

Computer Science: A Structured Programming Approach Using C 29 Computer Science: A Structured Programming Approach Using C 30

Sample program:
String Library Functions (ctype.h) #include <stdio.h>
#include <ctype.h>
 isalpha  toupper (character) int main()
{
 isalpha (‘A’) returns 1  toupper (‘g’) returns ‘G’
int i;
char name[3]="Ab4";
 isalpha (‘4’) returns 0  toupper (‘G’) returns ‘G’ for(i=0; i<3; i++)
{
 isupper printf("Index[%d] which is %c\n", i, name[i]);

 isupper (‘A’) returns 1  tolower (character) if(isalpha(name[i]))


printf(">>Is an alphabet\n");
 isupper (‘a’) returns 0  tolower (‘Q’) returns ‘q’ if(isupper(name[i]))
printf(">>Is an uppercase. The lowercase is %c \n", tolower(name[i]));
 islower (character)  tolower (‘q’) returns ‘q’ if(islower(name[i]))
printf(">>Is a lowercase. The uppercase is %c \n", toupper(name[i]));
 islower (‘A’) returns 0 if(isdigit(name[i]))
printf(">>Is a digit\n"); Index[0] which is A
 islower (‘a’) returns 1 >>Is an alphabet
printf("\n"); >>Is an uppercase.The lowercase is a
 isdigit (character) } The uppercase is A
return 0; Index[1] which is b
 isdigit (‘A’) returns 0 } >>Is an alphabet
>>Is a lowercase.The uppercase is B
 isdigit (‘4’) returns 1
Index[2] which is 4
>>Is a digit
Press any key to continue
Computer Science: A Structured Programming Approach Using C 31 Computer Science: A Structured Programming Approach Using C 32

S-ar putea să vă placă și