Tuesday, October 18, 2016

String in C Programming Part-1

Last Update:

Recommended Cloud & Hosting: Cloudways, Hostinger & BlueHost
What is strings?

String is a sequence of characters. In previous we know character is a single alphabet/number/sign within single quotes. But a string is made by one or more characters within double quotes.

Example, “Hello”, “I want to be a programmer” are different strings. Do you remember that you have used printf(“Hello World\n”); statement to print Hello World in your terminal by using C? There, which you have used withing double quotes is a string with whitespace.

Declaration of Strings

char string_name[string_size];
or
char string_name[string_size] = "STRING";
or
Example:
char str[11]="Bangladesh";
Size of string must be greater than total characters and 1. Because, there has one null character at last in character array string.
String Input Process:
Generally we can input in string in 3 ways.

1. By using scanf() function:



#include <stdio.h>
int main()
{
 char ch[40];
 scanf("%s",ch);
 printf("%s",ch);
 return 0;
}

Limitations:
By using specifier %s scanf() function can input only one string. It can't input another string with whitespace. To solve this problem, we can use by replacing edit set conversion code or %[^\n] in %s.

Example: If we use the following statement, it can input more string with whitespace.
scanf("%[^\n]",ch);
Now run the following program in your c compiler.

#include <stdio.h>
int main()
{
    char ch[40];
    scanf("%[^\n]",ch);
    printf("%s\n",ch);
    return 0;
}
Remember, If you use scanf() function to input string, then you have to use only printf(), puts() to print this string. You can't use putchar() function.

About me


Elliyas Ahmed
Elliyas Ahmed

Hi, I am Elliyas Ahmed, the founder of ComProMath. I try to share what I learn.

Work With Me - SEO Expert, WordPress, Blogger Theme Developer on Fiverr

Lets Disucss on this Article

Don't try SPAMMING here! Submit your Feedback, Questions or Comment related to this Article. Read our Comment Policy.

No comments:

Submit your COMMENT here