赛派号

橱柜什么材质的比较好又实惠 Strings in C

Strings in C Previous Quiz Next Strings in C

A string in C is a one-dimensional array of char type, with the last character in the array being a "null character" represented by '\0'. Thus, a string in C can be defined as a null-terminated sequence of char type values.

Creating a String in C

Let us create a string "Hello". It comprises five char values. In C, the literal representation of a char type uses single quote symbols such as 'H'. These five alphabets put inside single quotes, followed by a null character represented by '\0' are assigned to an array of char types. The size of the array is five characters plus the null character six.

Example char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; Initializing String Without Specifying Size

C lets you initialize an array without declaring the size, in which case the compiler automatically determines the array size.

Example char greeting[] = {'H', 'e', 'l', 'l', 'o', '\0'};

The array created in the memory can be schematically shown as follows −

If the string is not terminated by "\0", it results in unpredictable behior.

Note: The length of the string doesnt include the null character. The library function strlen() returns the length of this string as 5.

Loop Through a String

You can loop through a string (character array) to access and manipulate each character of the string using the for loop or any other loop statements.

Example

In the following example, we are printing the characters of the string.

#include #include int main (){ char greeting[] = {'H', 'e', 'l', 'l', 'o', '\0'}; for (int i = 0; i < 5; i++) { printf("%c", greeting[i]); } return 0; } Output

It will produce the following output −

Hello Printing a String (Using %s Format Specifier)

C provides a format specifier "%s" which is used to print a string when you're using functions like printf() or fprintf() functions.

Example

The "%s" specifier tells the function to iterate through the array, until it encounters the null terminator (\0) and printing each character. This effectively prints the entire string represented by the character array without hing to use a loop.

#include int main (){ char greeting[] = {'H', 'e', 'l', 'l', 'o', '\0'}; printf("Greeting message: %s\n", greeting ); return 0; } Output

It will produce the following output −

Greeting message: Hello

You can declare an oversized array and assign less number of characters, to which the C compiler has no issues. However, if the size is less than the characters in the initialization, you may get garbage values in the output.

char greeting[3] = {'H', 'e', 'l', 'l', 'o', '\0'}; printf("%s", greeting); Constructing a String using Double Quotes

Instead of constructing a char array of individual char values in single quotation marks, and using "\0" as the last element, C lets you construct a string by enclosing the characters within double quotation marks. This method of initializing a string is more convenient, as the compiler automatically adds "\0" as the last character.

Example #include int main() { // Creating string char greeting[] = "Hello World"; // Printing string printf("%s\n", greeting); return 0; } Output

It will produce the following output −

Hello World String Input Using scanf()

Declaring a null-terminated string causes difficulty if you want to ask the user to input a string. You can accept one character at a time to store in each subscript of an array, with the help of a for loop −

Syntax for(i = 0; i < 6; i++){ scanf("%c", &greeting[i]); } greeting[i] = '\0'; Example

In the following example, you can input a string using scanf() function, after inputting the specific characters (5 in the following example), we are assigning null ('\0') to terminate the string.

printf("Starting typing... "); for (i = 0; i < 5; i++) { scanf("%c", &greeting[i]); } // Assign NULL manually greeting[i] = '\0'; // Printing the string printf("Value of greeting: %s\n", greeting); Output

Run the code and check its output −

Starting typing... Hello Value of greeting: Hello Example

It is not possible to input "\0" (the null string) because it is a non-printable character. To overcome this, the "%s" format specifier is used in the scanf() statement −

#include #include int main (){ char greeting[10]; printf("Enter a string:\n"); scanf("%s", greeting); printf("You entered: \n"); printf("%s", greeting); return 0; } Output

Run the code and check its output −

Enter a string: Hello You entered: Hello

Note: If the size of the array is less than the length of the input string, then it may result in situations such as garbage, data corruption, etc.

String Input with Whitespace

scanf("%s") reads characters until it encounters a whitespace (space, tab, newline, etc.) or EOF. So, if you try to input a string with multiple words (separated by whitespaces), then the C program would accept characters before the first whitespace as the input to the string.

Example

Take a look at the following example −

#include #include int main (){ char greeting[20]; printf("Enter a string:\n"); scanf("%s", greeting); printf("You entered: \n"); printf("%s", greeting); return 0; } Output

Run the code and check its output −

Enter a string: Hello World! You entered: Hello String Input Using gets() and fgets() Functions

To accept a string input with whitespaces in between, we should use the gets() function. It is called an unformatted console input function, defined in the "stdio.h" header file.

Example: String Input Using gets() Function

Take a look at the following example −

#include #include int main(){ char name[20]; printf("Enter a name:\n"); gets(name); printf("You entered: \n"); printf("%s", name); return 0; } Output

Run the code and check its output −

Enter a name: Sachin Tendulkar You entered: Sachin Tendulkar

In newer versions of C, gets() has been deprecated. It is potentially a dangerous function because it doesnt perform bound checks and may result in buffer overflow.

Instead, it is advised to use the fgets() function.

fgets(char arr[], size, stream);

The fgets() function can be used to accept input from any input stream, such as stdin (keyboard) or FILE (file stream).

Example: String Input Using fgets() Function

The following program uses fgets() and accepts multiword input from the user.

#include #include int main(){ char name[20]; printf("Enter a name:\n"); fgets(name, sizeof(name), stdin); printf("You entered: \n"); printf("%s", name); return 0; } Output

Run the code and check its output −

Enter a name: Virat Kohli You entered: Virat Kohli Example: String Input Using scanf("%[^\n]s")

You may also use scanf("%[^\n]s") as an alternative. It reads the characters until a newline character ("\n") is encountered.

#include #include int main (){ char name[20]; printf("Enter a name: \n"); scanf("%[^\n]s", name); printf("You entered \n"); printf("%s", name); return 0; } Output

Run the code and check its output −

Enter a name: Zaheer Khan You entered Zaheer Khan Printing String Using puts() and fputs() Functions

We he been using printf() function with %s specifier to print a string. We can also use puts() function (deprecated in C11 and C17 versions) or fputs() function as an alternative.

Example

Take a look at the following example −

#include #include int main (){ char name[20] = "Rakesh Sharma"; printf("With puts(): \n"); puts(name); printf("With fputs(): \n"); fputs(name, stdout); return 0; } Output

Run the code and check its output −

With puts(): Harbhajan Singh With fputs(): Harbhajan Singh Print Page Previous Next Advertisements

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至lsinopec@gmail.com举报,一经查实,本站将立刻删除。

上一篇 没有了

下一篇没有了