A string in C is simply an array of characters. The following line declares an array that can hold a string of up to 99 characters.
char str[100];
It holds characters as you would expect: str[0]
is the first character of the string, str[1]
is the second character, and so on. But why is a 100-element array unable to
hold up to 100 characters? Because C uses null-terminated strings, which
means that the end of any string is marked by the ASCII value 0 (the null
character), which is also represented in C as '\0'.
The string I/0 operations (gets, puts, and so on) are implemented in <stdio.h>, and a set of fairly simple string manipulation functions are implemented in <string.h> (on some systems, <strings.h> ).
#include<stdio.h>
#include<string.h>
void main()
{
char name[100];
printf("Enter your name:");
gets(name);
printf("Assalamualikum mr/ms:");
puts(name);
}
Hint : is same as : #include<stdio.h>
#include<string.h>
void main()
{
char name[100];
printf("Enter your name:");
scanf(%s,name);
printf("Assalamualikum mr/ms:%s",name);
}
If you want to copy the contents of one string to another, the string library (<string.h> or <strings.h> ) contains a function called strcpy for this task.
char s[100];
strcpy(s, "yosof");
The following code shows how to use strcpy
in C: #include<stdio.h>
#include<string.h>
void main()
{
char s1[100],s2[100];
strcpy(s1,"yosof"); /* copy "yosof" into s1 */
printf("s1 is %s\n",s1);
strcpy(s2,s1); /* copy s1 into s2 */
printf("s2 is %s\n",s2);
}
strcpy is used whenever a string is
initialized in C. You use the strcmp
function in the string library to compare two strings. It returns an integer
that indicates the result of the comparison. Zero means the two strings are
equal, a negative value means that s1 is less than s2, and a
positive value means s1 is greater than s2.
#include <stdio.h>
#include <string.h>
void
main()
{
char
s1[100],s2[100];
printf("Enter
value for s1:");
gets(s1);
printf("Enter
value for s2");
gets(s2);
if
(strcmp(s1,s2)==0)
{
printf("equal\n");
}
else
if (strcmp(s1,s2)<0)
{
printf("s1 less than
s2\n");
}
else
{
printf("s1 greater than
s2\n");
}
}
#include<stdio.h>
#include <string.h>
void main()
{
char stringOne[255];
char stringTwo[255];
stringOne[0]='\0';
stringTwo[0]='\0';
printf("Enter a string:");
gets(stringOne);
printf("Enter a second string:");
gets(stringTwo);
printf("String One: %s\n",stringOne);
printf("String Two: %s\n",stringTwo);
strcat(stringOne," ");
printf("String One: %s\n",stringOne);
strncat(stringOne,stringTwo,10);
printf("String One: %s\n",stringOne);
printf("String Two: %s\n",stringTwo);
}
#include<stdio.h>
#include <string.h>
void main()
{
int
length;
char
name[100];
printf("Enter
your name:");
gets(name);
length=strlen(name);
printf("For
%s no of character is %d\n",name,length);
}
No comments:
Post a Comment