String is a collection of characters that are used to represent textual data.
int main() {
char str[] = "Sujith";
printf("%s", str);
return 0;
}
- Use
%s
format specifier for printing string. - Every string in c ends with \0. This null character helps the compiler to know the end of the string. So actual size of the string will be 1 greater than the total no;of character in the string.
String Input
int main() {
char str[20];
printf("Enter your name here: ");
scanf("%s", str);
printf("%s", str);
return 0;
}
In order to take the input, we don't need to use &
for string because str
is an array and it already points to the first element of str
.
The scanf method can only take input until it encounters white spaces. So not possible to take input like "Steve Jobs". So to take all the inputs we can use:
fgets(str, sizeof(str), stdin)
str - string name
sizeof(str) - size of string.
stdin - it means standard input. It denotes we are taking input from the keyboard.
Access characters of string
int main() {
char str[] = "Sujith";
printf("%c", str[0]);
return 0;
}
Since we are only printing single character use %c format specifier
Changing elements of a string.
int main() {
char str[] = "Sujith";
str[2] = 'J';
str[4] = 'T';
printf("%s", str);
return 0;
}
Top comments (0)