arrays and stringsteacher.buet.ac.bd/mdmamun/string.pdf · 1 strings while c supplies the data type...
TRANSCRIPT
1
Strings
While C supplies the data type char, it does not have a
data type for character strings;
A character string must be represented as one of the
following:
As an array of characters: char myname[20];
As a pointer to char: char *p;
As a string literal: "Hi There!"
All three representations are pointers to char.
The array uses one cell for each character in the string,
with the final cell holding the null character ‘\0’
2
Strings
The C-string "Hi there!" would be stored in memory as
shown:
Note that for each array, there are one more cells than the
number of characters
When you use double quotes to list the initial values of the
character array, the system will automatically add the null
terminator ‘\0’
Using an unsized array is better in these cases
Remember that the array’s dimension must be large
enough to hold the string along with the null terminator
3
Strings
/* A C program to read string from console / terminal */
#include <stdio.h>
int main( )
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}
/* Program Output*/ Enter name: Abdus Salam
Your name is Abdus.
4
Strings
/* Program to read read line of text manually from console / terminal */
#include <stdio.h>
int main(){
char name[30],ch;
int i=0;
printf("Enter name: ");
while(ch!='\n') { // terminates if user hit enter
ch=getchar();
name[i]=ch;
i++; }
name[i]='\0'; // inserting null character at end
printf("Name: %s.”, name);
return 0;
}
/* Program Output*/ Enter name: Abdus Salam //hit enter
Your name is Abdus Salam.
5
Strings
/* Predefined functions gets() and puts() to read and display string
respectively from console / terminal */
int main()
{
char name[30];
printf("Enter name: ");
gets(name); //Function to read string from user.
printf("Name: ");
puts(name); //Function to display string.
return 0;
}
/* Program Output*/ Enter name: Abdus Salam //hit enter
Your name is Abdus Salam.
6
Strings
#include <stdio.h>
int main ( ) {
char water_state1 [4] = {‘g’,’a’,’s’,’\0’}; //null terminated character array, i.e. a string
char water_state2 [6]; // if null terminated, then represents a 5 character string
char water_state3 [7] = “liquid”; // character array initialized with string literals
printf (“\n\tPlease enter the water state: ”);
scanf (“%s”, water_state2);
printf (“%s\n”, water_state1);
printf (“%s\n”, water_state2);
printf (“%s\n”, water_state3);
return 0;
}
/* Program Output*/ Please enter the water state: // type solid and hit enter
gas
solid
liquid.
7
Strings
Note that in the scanf function, water_state2 was not
preceded by the address operator &
Unlike simple variable names, array’s name is an address
expression – the address of the first element in the array
Remember that strings are character arrays terminated
by a null character ‘\0’. But character arrays without a
terminating null character is possible. Therefore,
although “all strings are character arrays but all character
arrays are not strings”.
8
Strings
Array of char can be defined and initialized to a C-string
char str1[20] = "hi";
A pointer to a string can be declared and then initialized
to a C-string
char *pStr;
pStr = "hello there!";
Array of char can be defined and later have a string
copied into it
char str2[20];
strcpy(str2, "hi");
9
Strings
Library Functions for Working with C-Strings require
<string.h> header file
Functions take one or more C-strings as arguments.
Argument can be:
Name of an array of char
pointer to char
literal string
int strlen(char *str) - returns length of a C-string:
int n = strlen("hello"); // n = 5
Note: This is the number of characters in the string, NOT
the size of the array that contains it
10
Strings
strcat(char *dest, char *source) - takes two C-strings as
input. It adds the contents of the second string to the
end of the first string:
char str1[15] = "Good ";
char str2[30] = "Morning!";
strcat(str1, str2);
printf ( “%s”, str1); // prints: Good Morning!
No automatic bounds checking: programmer must
ensure that str1 has enough room for result
11
Strings
strcpy(char *dest, char *source) - copies a string from a
source address to a destination address
char name[15];
strcpy(name, "Deborah");
printf (“%s”, name); // prints Deborah
Using pointer to string:
char *p;
strcpy(p, "Deborah");
printf (“%s”, p); // prints Deborah
12
Strings
int strcmp(char *str1, char*str2) - compares strings stored
at two addresses to determine their relative alphabetic
order:
Returns a value:
less than 0 if str1 precedes str2
equal to 0 if str1 equals str2
greater than 0 if str1 succeeds str2
Often used to test for equality
if(strcmp(str1, str2) == 0)
printf (“equal“);
else
printf ("not equal“);
13
Strings
strcmp is also used to determine ordering of C-strings in
sorting applications
Note that C-strings cannot be compared using == (compares
addresses of C-strings, not contents)
char *strstr(char *str1, char *str2) - searches for the
occurrence of str2 within str1.
Returns a pointer to the occurrence of str2 within str1 if
found, and returns NULL otherwise
char s[15] = "Abracadabra";
char *found = strstr(s, "dab");
printf(“%s”, found); // prints dabra
14
Strings
char *strchr(char *str1, char ch) - searches for the
occurrence of ‘ch’ within str1.
Returns a pointer to the first occurrence of ‘ch’ within str1 if
found, and returns NULL otherwise
char *p1, *p2;
char s[15] = "Abracadabra";
p1 = strchr(s, ‘d’);
if (p1 == NULL) printf(“\n no match found”);
printf(“ \’ %c \’ found”, *p1); // prints ‘d’ found
p2 = strchr(s, ‘t’);
if (p2 == NULL) printf(“\n no match found”);
printf(“%c found”, *p2); // prints no match found
15
Strings
char *strlwr(char *str) - Converts string ‘str’ to lowercase
char *strupr(char *str) - Converts string ‘str’ to uppercase
char *p1, *p2;
char s[15] = "Abracadabra";
p1 = strupr(s);
printf(“ %s \n”, p1); // prints ABRACADABRA
p2 = strlwr(s);
printf(“%s \n”, p2); // prints abracadabra
16
Strings
/* Program to sort words in Dictionary Order from console / terminal */
#include<stdio.h>
#include <string.h>
int main(){
int i,j;
char str[10][50],temp[50];
printf("Enter 10 words:\n");
for(i=0;i<10;++i)
gets(str[i]);
for(i=0;i<9;++i)
for(j=i+1;j<10 ;++j){
if(strcmp(str[i],str[j])>0)
{
strcpy(temp,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],temp);
17
Strings
}
}
printf("In lexicographical order: \n");
for(i=0;i<10;++i){
puts(str[i]);
}
return 0;
}
/* Program Output*/
Enter 10 words:
fortran
java
perl
python
php
javascript
18
Strings
c
cpp
ruby
csharp
In lexicographical order:
c
cpp
csharp
fortran
java
javascript
perl
php
python
ruby
19
Strings
Conversion Functions can be used to convert between string
and numeric forms of numbers. These functions require
<stdlib.h> header file
atoi() converts alphanumeric to int
atol() converts alphanumeric to long
Prototypes:
int atoi(char *numericStr)
long atol(char *numericStr)
Examples:
int number; long lnumber;
number = atoi("57");
lnumber = atol("50000");
20
Strings
atof() converts a numeric string to a floating point number,
actually a double
Prototype:
double atof(char *numericStr)
Example:
double dnumber;
dnumber = atof("3.14159");
if C-string being converted contains non-digits, results are
undefined
function may return result of conversion up to first non-digit
function may return 0
21
Strings
itoa() converts an int to an alphanumeric string
Allows user to specify the base of conversion
itoa(int num, char *numStr, int base)
Example: To convert the number 1200 to a hexadecimal
string
char numStr[10];
itoa(1200, numStr, 16);
The function performs no bounds-checking on the array
numStr
22
Strings
FUNCTION MEANING
isalpha() true if arg. is a letter, false otherwise
isalnum() true if arg. is a letter or digit, false otherwise
isdigit() true if arg. is a digit 0-9, false otherwise
islower() true if arg. is lowercase letter, false
otherwise
Character Testing Functions: - require <ctype.h> The following functions takes a single character as argument, e.g., isalpha(‘z’); //Output: true, i.e., 1
23
Strings
FUNCTION MEANING
isprint() true if arg. is a printable character, false
otherwise
ispunct() true if arg. is a punctuation character, false otherwise
isupper() true if arg. is an uppercase letter, false
otherwise
isspace() true if arg. is a whitespace character, false
otherwise
24
Strings
FUNCTION MEANING
toupper() convert a single letter to uppercase equivalent.
if char argument is lowercase letter, return
uppercase equivalent; otherwise, return input unchanged
tolower() convert a single letter to lowercase equivalent.
if char argument is uppercase letter, return
lowercase equivalent; otherwise, return input unchanged
Character Case Conversion Functions - require <ctype.h> Examples: toupper(‘z’); //Output: Z toupper(‘Z’); //Ouput: Z
25
Strings
Character Case Conversion Functions - Examples - require <ctype.h> header file
char s[] = "Hello!";
printf(“%c”, toupper(s[0]); //displays 'H'
printf(“%c”, toupper(s[1]); //displays 'E'
printf(“%c”, toupper(s[5]); //displays '!'
char s[] = "Hello!";
printf(“%c”, tolower(s[0]); //displays 'h'
printf(“%c”, tolower(s[1]); //displays 'e'
printf(“%c”, tolower(s[5]); //displays '!'
26
Strings
Standard input and output functions that use character arrays as function arguments are:
gets(), puts() // console I/O functions
fgets(), fputs() // file I/O functions
sscanf(), sprintf () // string I/O functions
The following program uses string I/O functions
#include <stdio.h>
#define SIZE 20
int main ( ) {
char test_array [SIZE];
27
Strings
fputs (“Please enter the first string : “, stdout);
gets (test_array);
fputs (“The first string entered is : “, stdout);
puts (test_array);
fputs (“Please enter the second string : “, stdout);
fgets (test_array, SIZE, stdin);
fputs (“The second string entered is : “, stdout);
fputs (test_array, stdout);
sprintf (test_array, “This was %s a test”, “just”);
fputs (“sprintf() created : “, stdout);
fputs (test_array, stdout);
return 0;
}
28
Strings
The output from the first run of the program looks like:
Please enter the first string : string one
The first string entered is : string one
Please enter the second string : string two
The second string entered is : string two
sprintf() created : This was just a test
Take care when running the program
The gets() function receives characters from standard input (stdin, the keyboard by default) and places them into the array whose name is passed to the function
When one presses ENTER to terminate the string, a newline character is transmitted which is changed into a null character by gets() function
29
Strings
The puts() function echoes to the terminal just what was entered with gets()
When you use the fgets() function, you can guarantee a maximum number of input characters
This function stops reading the designated file stream when one fewer characters are read than the second argument specifies
The fgets() function does not eliminate the newline character, as gets() did, but merely appends the null character so that a valid string is stored
Much like gets() and puts(), fgets() and fputs() are symmetrical
fgets() does not eliminate the newline character, nor does fputs () add one
30
Strings
The function sprintf(), which stands for ‘string printf()’, uses
a control string with conversion characters, just like printf()
However, sprintf() places the resulting formatted data in a
string rather than immediately sending the result to the
standard output
This can be beneficial if the exact same output must be
created twice – for example, when the same string must
be output to both the display monitor and the printer
Likewise, the function sscanf(), stands for ‘string scanf()’, uses a
control string with conversion characters, just like scanf()
However, sscanf() scans for the specified formatted data in
a string rather than receiving the data from the standard input
This helps to compress the input data by eliminating characters
which are used in the input buffer only as data separators.
31
Strings
Syntax:
sprintf ( char *string, “control string”,
variables/expression/constants ) ;
sscanf ( char *string, “control string”, &variables ) ;
Example: Given, i = 10, f = 3.50, string2[] = “20 3.75”
sprintf (string1, “%d %f\n”, i, f); //string1 = “10 3.50”;
sscanf (string2, “%d %f”, &i, &f); // i = 20; f = 3.75;
Here, sprintf() places the formatted output to the string1,
NOT to the standard output (display)
Similarly, sscanf() reads data from the string2, NOT from the
standard input (keyboard)
32
Strings
// Program 1
#include <stdio.h>
#include <string.h>
#define WORD_LENGTH 6
#define STRING_LENGTH 20
int main ()
{
char part1 [WORD_LENGTH] = "In",
part2 [WORD_LENGTH] = " the ",
prologue [STRING_LENGTH];
strcpy (prologue, part1);
strcat (prologue, part2);
strcat (prologue, "beginning ... ");
33
Strings
printf ("%s\n", prologue);
return 0;
}
// Program 2
#include <stdio.h>
#include <string.h>
int main ()
{
char string1 [] = "one", string2 [] = "one";
int result = 0;
34
Strings
if (strlen (string2) >= strlen (string1))
result = strcmp (string1, string2);
printf ("The string %s", result == 0 ? "was" : "wasn't");
printf (" found to be equal");
return 0;
}
The first program outputs
In the beginning ...
And the second program outputs
The string was found to be equal
35
Strings
// Program to PLOT a function in Text Mode Output Screen
#include <stdio.h>
#include <math.h>
#define X_MAX 76 //X_MAX = 60, VERTICAL RESOLUTION (ROW), 0 AT TOP LEFT
#define Y_MAX 31 //Y_MAX = 80, HORIZONTAL RESOLUTION (COLUMN), 0 AT TOP LEFT
#define SYMBOL 'o'
#define X_TITLE "Compression Ratio, r (8 to 12)"
#define Y_TITLE "Efficiency (56% to 71%)"
#define PLOT_TITLE "FIGURE: Otto Cycle Efficiency vs Compression Ratio"
#define Y_F(X) 100*(1 - (1 /(pow((X), 0.4)))) //MACRO FUNCTION: ARGUMENTS ALWAYS NEED
PARENTHESIS
36
Strings
int main(){
char plot[X_MAX][Y_MAX];
int x, y;
for (x = 0; x < X_MAX; x++){
for(y = 0; y < Y_MAX; y++){
plot[x][y] = ' ';
}
}
printf("\n\n");
for(x = 8; x <= 22; x++) {
y = (int) roundf (Y_F(x)); //THE EXPRESSION IS TYPE CASTED TO INT
plot[X_MAX - y][Y_MAX - x] = SYMBOL; //BOTH AXIS INVERSIONS //ARE DONE TO PLOT
//BOTTOM UP
}
37
Strings
for (x = 0; x < 31; x++) {
plot[x][25] = '|';
}
printf("\n\n\t%s", Y_TITLE );
for (x = 0; x < 25; x++) {
printf("\n\t");
for(y = 26; y > 5; y--){
printf("%c ", plot[x][y]);
}
}
printf("\n\t _______________________________________________");
printf("\n\n\t\t\t%s", X_TITLE);
printf("\n\n\t %s\n\n", PLOT_TITLE );
printf("\n\n");
return 0;
}
38
Strings
// Output of the previous PLOT program in Text Mode Output Screen
39
Strings
// Let us PLAY a simple WORDGAME
#include <stdio.h>
#include <stdlib.h> //DECLARES SRAND(), RAND(), SYSTEM() FUNCTIONS
#include <string.h>
#include <ctype.h>
#include <time.h> //DECLARES TIME() FUNCTION
char *newword(); //FUNCTION PROTOTYPE TO GENERATE NEW WORD
int main(){ //MAIN GAME ENGINE
char ch, ch1, choice;
char gameword[20]={'\0'}; //MAIN GAMEWORD
char guesses[20]={'\0'}; //PLAYER GUESSWORD
int n, i, j, trial, check_repeat, repeat=0, ok =0;
srand(time(NULL));
40
Strings
for (; ;) {
sprintf(gameword, "%s", newword()); //SAVES A NEW WORD TO 'gameword'
n = strlen(gameword);
trial = n + 5; //TOTAL NUMBER OF GUESSES ALLOWED TO THE PLAYER
system("cls"); //SYSTEM COMMAND TO CLEAR THE OUTPUT SCREEN
printf("\n\n\n");
printf("\n\tGuess a country name of %d characters\n\n\t\tpress enter after each character...(a - z):\n\n\n\t ", n);
for(j = 1; j <= trial; j++){
printf("\n\n\t\t");
ch = toupper(getchar());
ch1=getchar();
check_repeat = 0;
41
Strings
for(i = 0; i < n; i++){
if(ch == gameword[i]){
guesses[i]= ch;
ok++; //COUNTS TOTAL NUMBER OF CORRECT GUESSES
check_repeat++;
if(check_repeat>1) repeat++;
}
}
system("cls");
printf("\n\n\t\t");
for(i = 0; i <= n; i++)printf("%c", guesses[i]);
printf("\t\t(%d characters remain)\n", (n - ok));
printf("\n\n\t\t%d guesses remain...\n", trial-j);
printf("\n\t\tCorrect guesses: %d", ok);
printf("\t\tMisses: %d\n\n\n\n\t", (j - ok));
42
Strings
if(strcmp(guesses, gameword) == 0) goto exit1;
}
system("cls");
printf("\n\n\t\t");
for(i = 0; i <= n; i++) printf("%c", gameword[i]);
printf("\t\t(%d characters remained...)\n", (n - ok));
printf("\n\n\t\tYou have lost!!...Try out next time...\n");
printf("\n\n\t\t%d guesses remained...\n", trial - j);
printf("\n\t\tCorrect guesses: %d", ok);
printf("\t\tMisses: %d\n\n\n\n\t", (j - ok));
goto end;
exit1:
system("cls");
printf("\n\n\t\t");
43
Strings
for(i = 0; i <= n; i++) printf("%c", gameword[i]);
printf("\n\n\t\tCongrats!! You have won!!!");
printf("\n\n\t\t%d guesses remained...\n", trial - j);
printf("\n\t\tCorrect guesses: %d", ok);
printf("\t\tMisses: %d", (j - ok));
end:
printf("\n\n\t\tPlay again? (Y/N) ");
choice = toupper(getchar());
if( choice == 'N')break;
for(i=0; i<20; i++) guesses[i]='\0';
ok=0;
}
printf("\n\n");
return 0;
} // MAIN GAME ENGINE ENDS HERE
44
Strings
char *newword() { //FUNCTION RETURN TYPE IS POINTER TO STRING
int m; //USE THIS FUNCTION TO EXTEND THE GAME
select:
m = rand()%11;
switch(m) {
case 0: goto select;
case 1: return "BANGLADESH";
case 2: return "BHUTAN";
case 3: return "JAPAN";
case 4: return "SRILANKA";
case 5: return "SINGAPORE";
case 6: return "ARGENTINA";
case 7: return "BRAZIL";
case 8: return "AUSTRALIA";
case 9: return "IRAQ";
case 10: return "PALESTINE"; } }
45
Strings
// Output of the WORDGAME at different steps