13 ES 26 - Strings
13 ES 26 - Strings
13
Introduction to Programming
Strings
Introduction to Programming
Implicit Strings
W e l c o m e \n \0
Introduction to Programming
Implicit Strings
• Why implicit?
The program does not have any control
over the size or number of elements
in the array, which was implicitly
sized by the compiler.
Introduction to Programming
Variable/Explicit Strings
Introduction to Programming
Examples
char first_name[5] = {‘J’,’u’,’a’,’n’,’\0’};
– previous rules on arrays still apply
Introduction to Programming
Examples
char other[100] = “Maria Makiling”;
– specifying a larger size leaves space in the
array for other characters to be appended
– compiler still appends '\0' after the implicit
string
Introduction to Programming
Printing Strings
• Strings can be printed per element as
they are just arrays:
int i;
char cool[] = “Programming”;
while(cool[i] != ‘\0’)
printf(“%c”, cool[i++]);
Introduction to Programming
Printing Strings
Introduction to Programming
Accepting/Reading Strings
• Using scanf()
scanf( “%s”, cool );
Introduction to Programming
Accepting/Reading Strings
• Same as
scanf( “%s”, &name[0] );
Introduction to Programming
Example – gets()
...
puts(“Anong pangalan mo? ”);
gets( string );
printf(“Ikaw si ”);
puts( string);
...
Introduction to Programming
Assigning to String
• Valid (initialization)
– char who[] = “Ser Wilmarc”;
• Invalid
– who = “Mom Wilmarc”;
Introduction to Programming
Assigning to String
#include <stdio.h>
#include <string.h>
main(void)
{
char who[20];
strcpy(who, “Manong Fishball”);
strcpy(who, “Tuition Fee Increase”);
printf(“%s”,who);
return 0;
}
Introduction to Programming
String Handling Functions in
string.h
char s1[50] = “UP”;
char s2[50] = “UP System”;
strcpy(s1,“Hello”);
strcat(s1, “ world!”);
printf(“%s”,s1);
Introduction to Programming
String Handling Functions in
string.h
strcmp(s1,s2) – an integer is returned
that is less than, equal to or greater
than zero, depending on whether s1
is lexicographically less than, equal
to, or greater than s2, respectively.
– Both can either be implicit or explicit
strings.
strcmp(“Hello”,”Hell”); >0
strcmp(“Hell”, “Hello”); <0
strcmp(“Sat”,”Cat”); >0
Introduction to Programming
Lab Exercises
Introduction to Programming