Lecture 18
Lecture 18
char x= "A"; The double quotation marks are used to delimit the character
string, which can contain any combinations of letters, numbers,
char x= 'A'; or special characters
printf(" Hello ");
To assign a single character to such a variable, the character is
printf(' Hello '); enclosed within a pair of single quotation marks
#include <stdio.h> Concatenating strings
void concat (char result[], const char str1[], const char str2[]);
int main (void)
{
const char s1[] = { “Jibt " };
const char s2[] = { “5obiz???" };
Jibt 5obiz???
char s3[20];
concat (s3, s1, s2);
printf ("%s\n", s3);
return 0;
}
// Function to concatenate two character strings
void concat (char result[], const char str1[], const char str2[])
{
int i, j;
for ( i = 0; str1[i] != '\0'; ++i ) // copy str1 to result
result[i] = str1[i];
for ( j = 0; str2[j] != '\0'; ++j ) // copy str2 to result
result[i + j] = str2[j];
result [i + j] = '\0'; // Terminate the concatenated string with a null character
}
#include <stdio.h>
#include <stdbool.h> //makes it easy to work with bool
Are strings equal??
bool equalStrings (const char s1[], const char s2[])
{
int i = 0;
bool areEqual;
while ( s1[i] == s2 [i] && s1[i] != '\0' && s2[i] != '\0' )
++i;
if ( s1[i] == '\0' && s2[i] == '\0' )
areEqual = true;
else 0
areEqual = false; 1
return areEqual; 1
}
int main (void)
{
char stra[] = “esm3";
char strb[] = “m3allem";
printf ("%i\n", equalStrings (stra, strb));
printf ("%i\n", equalStrings (stra, stra));
printf ("%i\n", equalStrings (strb, " m3allem "));
return 0;
}
Input strings from user
// Program to illustrate the %s scanf format characters
#include <stdio.h>
Enter text:
int main (void) Elmaddeh men
el2aa5er
{ s1 = Elmaddeh
s2 = men
char s1[], s2[], s3[]; s3 = el2aa5er
printf ("Enter text:\n");
scanf ("%s%s%s", s1, s2, s3);
printf ("\ns1 = %s\ns2 = %s\ns3 = %s\n", s1, s2, s3);
return 0;
}