Strings Chap 8
Strings Chap 8
A v e r a g e = % . 2 f
• A string of 14 characters,
String Basics - no. of characters
• printf(“Hello! Good day”);
H e l l o ! G o o d d a y
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
• A string of 15 characters,
String Basics - Declaration
Case 1:
char vari[10];
vari[10] = “Greeting!”;
Case 2:
char vari[10] = “Greeting!”;
String Basics - Declaration
• char string_var[6] = “value”;
v a l u e 5
Refer to charac
address of [0] ters
[0] [1] [2] [3] [4]
to [4]
Refer to
address of [0] [] [0] [1] [2] [3] [4]
to [4]
Length-controlled
string
String Basics - Declaration
• char vart[10] = “Hello!”;
End of
10 H e l l o ! \0 string
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
Adddress
[0] to [9]
String Basics - Declaration
• char str[20] = “Initial value”;
I n i t i a l v a l u e \0 ? ? ? ? ? ?
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14] [15] [16] [17] [18] [19]
String Basics - %c and %s - printf
• Case 1: use %c
• Use for loop to print out the string.
for(i=0; i<5; i++)
printf(“%c”, str[i]);
• Case 2: use %s
• For loop is not required.
printf(“%s”, str);
String Basics - %c and %s - scanf
• Case 1: use %c
• Use for loop to store the string in an array.
• A specific address “&” is required.
for (int i=0; i<10; i++ )
scanf("%c", &string_val[i]);
• Case 2: use %s
• Both for loop and & are not required.
scanf(“%s”, str);
String Basics – limitation of scanf
String Basics – Solve %c & %s
limitations
• Function gets() and puts();
printf("Enter a char:");
str01 = getchar();
printf("%c", str01);
ctype.h function – isalpha()
char str01;
printf("Enter a char:");
str01 = getchar();
if (isalpha(str01))
printf("It is a %c", str01);
else
printf("It is not a character");
ctype.h function – isdigit()
char str01;
printf("Enter a number:");
str01 = getchar();
if (isdigit(str01))
printf("\nIt is a digit");
else
printf("\nIt is not a digit");
ctype.h function – islower()
char str01;
printf("Enter a char:");
str01 = getchar();
if (islower(str01))
printf("It is a lower case character");
else
printf("It is an upper case character");
ctype.h function – isupper()
char str01;
printf("Enter a char:");
str01 = getchar();
if (isupper(str01))
printf("It is an upper case character");
else
printf("It is a lower case character");
ctype.h function – ispunct()
char str01;
printf("Enter a char:");
str01 = getchar();
if (ispunct(str01))
printf("It is a punctuation");
else
printf("It is not a punctuation");
ctype.h function – isspace()
char str01;
printf("Enter a char:");
str01 = getchar();
if (isspace(str01))
printf("It is a space");
else
printf("It is not a space");
ctype.h function – tolower()
char str01;
printf("Enter a char:");
str01 = getchar();
printf("To lower case: %c", tolower(str01));
ctype.h function – toupper()
char str01;
printf("Enter a char:");
str01 = getchar();
printf("To upper case: %c", toupper(str01));
sprintf() function in stdio.h