2D Array Strings
2D Array Strings
– Representation in C
– String Literals
– String Variables
– String Input/Output
• printf, scanf, gets, fgets, puts, fputs
– String Functions
• strlen, strcpy, strncpy, strcmp, strncmp, strcat, strncat, strchr,
strrchr, strstr, strspn, strcspn, strtok
– Reading from/Printing to Strings
• sprintf, sscanf
“Hello” H e l l o ‘\0’
• Examples
– represents empty string
– hello
• Example:
printf(”%c”, ”hello”[1]);
outputs the character ‘e’
char name[30];
char city[15];
char dob[11];
• Example:
char *str1 = hello; /* str1 unchangeable */
char *str2 = goodbye; /* str2 unchangeable */
char line[81];
:
:
scanf (%[ ABCDEFGHIJKLMNOPQRSTUVWXYZ], line);
char line[81];
:
:
scanf (%[^\n], line);
• Examples:
scanf (%[+0123456789], Number);
scanf (%[^\n], Line); /* read until newline char */
char name[50];
:
:
printf (\n %s, name);
void main( )
{
char LastName[11];
char FirstName[11];
• Example:
len = strlen (string);
/* Returns an integer */
n is assigned 8
if (strcmp(city1, city2) != 0)
{ …… }
Works the same as strcmp except that it stops at the nth character
looks at less than n characters if either string is shorter than n
A m i t ‘\0’
• Example:
strcpy(name1, Amit ); R o y ‘\0’
strcpy(name2, Roy);
strcat(name1, name2);
A m i t R o y ‘\0’
Spring Semester 2020 Programming and Data Structure 29
Example:: count uppercase
/* Read a line of text and count the number of
uppercase letters */
#include <stdio.h>
#include <string.h>
main()
{
char line[81];
int i, n, count=0;
scanf (%[^\n], line);
n = strlen (line);
for (i=0; i<n; i++)
if (isupper(line[i]) count++;
printf (\n The number of uppercase letters in
the string %s is %d, line, count);
}
{
int i=0;
while(s1[i]!='\0' && s2[i]!='\0'){
if (s1[i]!=s2[i]) return(s1[i]-s2[i]);
else i++;
}
return(s1[i]-s2[i]);
}
Example:
char buffer[100];
sprintf (buffer, %s, %s, LastName, FirstName);
if (strlen(buffer) > 15)
printf(Long name %s %s\n, FirstName, LastName);
Example:
char buffer[100] = A10 50.0;
sscanf (buffer, %c%d%f, &ch, &inum, &fnum);
/* puts ‘A’ in ch, 10 in inum and 50.0 in fnum */
Student 1 75 82 90 65 76
Student 2 68 75 80 70 72
Student 3 88 74 85 76 80
Student 4 50 65 68 40 70
• General form:
type array_name[row_size][column_size];
• Examples:
int marks[4][5];
float sales[12][25];
double matrix[100][100];
a[0][0] a[0][1] a[0]2] a[0][3] a[1][0] a[1][1] a[1][2] a[1][3] a[2][0] a[2][1] a[2][2] a[2][3]
10 20 30
40 50 60
70 80 90
10 20 30
40 50 60
70 80 90
10 20 30
void transpose (x, n)
int x[][3], n; 40 50 60
{
int p, q, t; 70 80 90