String Programs In C

String in C Programming Language

This lesson will teach you about String Programs In C. With the help of examples, you’ll learn how to declare them, initialize them, and utilize them for various I/O tasks.

A string is a group of characters that ends with the null character “0” in C programming. The definition of a string is a collection of characters. A string differs from a character array in that it is finished with the distinctive letter “0.”

A string in C programming is a sequence of characters that ends with the null symbol 0. As an example:

char c[] = "c string";

When the compiler encounters a sequence of characters enclosed in double quotation marks, it defaults to appending a null character 0 at the end.

What is the proper way to declare a string in C Program?

Similar to declaring a one-dimensional array, a string can be declared easily. The fundamental syntax for declaring a string is shown below.

Here’s how you can declare strings:

char s[5];

In the syntax mentioned above, size is used to specify the string’s length or the number of characters it may hold. Str name is any name supplied to the string variable.

The Null character (‘0’), an additional terminating character that distinguishes strings from standard character arrays, is used to signify the end of a string. The compiler by default appends the null character “0” to the end of the string whenever it encounters a sequence of characters contained in double quotation marks.

We’ve declared a 5-character string here.

How should a string in C Program be initialized?

You can initialize strings in a number of ways.

char c[] = "abcd";

char c[50] = "abcd";

char c[] = {'a', 'b', 'c', 'd', '\0'};

char c[5] = {'a', 'b', 'c', 'd', '\0'};

Let’s take another example:

char c[5] = "abcde";

In this case, we’re attempting to assign a 6-character string (the final character is ‘0’) to a 5-character char array. You should never engage in behavior like this.

Values are Applied to Strings

In C, arrays and strings are considered second-class citizens since, once declared, they do not support the assignment operator. For instance,

char c[100];
c = "C programming";  // Error! array type is not assignable.

Note: To copy the string instead, use the strcpy() function.

Read the user-supplied string

The scanf() function can be used to read a string.

The scanf() function examines the characters one by one until it comes across whitespace (space, newline, tab, etc.).

Example 1: scanf() to read a string

#include <stdio.h>
int main()
{
    char name[20];
    printf("Enter name: ");
    scanf("%s", name);
    printf("Your name is %s.", name);
    return 0;
}

Output

Enter name: Dennis Ritchie
Your name is Dennis.

Dennis Ritchie was typed into the above application, but only “Dennis” was saved in the name string. It’s because Dennis was followed by a comma.

The string can alternatively be read using a single scanf statement, as seen in the program above. You may also be wondering why we did not use the ‘&’ sign in the scanf command with the string name “str”! You’ll need to think back to your scanf knowledge in order to comprehend this.

We are aware that the “&” symbol is used to tell the scanf() function where to save the value read from memory. Since str[] is a character array, the base address of this string can be found by using str without the braces “[” and “]”. Because we are already giving scanf the string’s base address, we have omitted the ‘&’ operator in this situation.

Additionally, you’ll see that we used scanf with code name rather than &name.

scanf("%s", name);

This is due to the fact that name is a char array, and in C, array names degenerate into pointers.

We don’t need to use & because the name in scanf() already points to the address of the string’s first element.

How should a line of text be read?

To read a line of text, use the fgets() method. To read characters from the standard input (stdin) and store them as a C string until a newline character or the End-of-file (EOF) is reached, use the gets() function.

The fgets() function can be used to read a line of a string. Additionally, you can display the string using puts().

Example 2: fgets() and puts()

#include <stdio.h>
int main()
{
    char name[30];
    printf("Enter name: ");
    fgets(name, sizeof(name), stdin);  // read string
    printf("Name: ");
    puts(name);    // display string
    return 0;
}

Output

Enter name: Tom Hanks
Name: Tom Hanks

The fgets() function was used to read a string from the user in this case.

read string; fgets(name, sizeof(name), stdlin);

Sizeof(name) yields a result of 30. Therefore, the maximum number of characters we may accept as input is 30, which is the length of the name string.

We used the expression puts(name); to print the string.

Note: the gets() function can also be used to receive user input. The C standard, however, does not include it anymore.
It’s because gets() lets you enter characters of any length. Consequently, a buffer overflow could occur.

Strings as Function Arguments

Similar to how arrays can be provided to a function, strings can also. Find out more about how to pass arrays to functions.

Example 3: Passing string to a Function(String Programs In C)

#include <stdio.h>
void displayString(char str[]);

int main()
{
    char str[50];
    printf("Enter string: ");
    fgets(str, sizeof(str), stdin);             
    displayString(str);     // Passing string to a function.    
    return 0;
}
void displayString(char str[])
{
    printf("String Output: ");
    puts(str);
}

Pointers and Strings(String Programs In C)

The variable name in arrays points to the first element’s address. We can establish a character pointer to a string, which points to the string’s initial location, which is the first character, similar to how we do with arrays in C. As demonstrated in the example below, pointers can be used to access the string.

String names “decay” to pointers in a manner similar to that of arrays. Consequently, you can manipulate the string’s elements using pointers. It is advised that you review C Arrays and Pointers before reviewing this example.

Example 4: Strings and Pointers(String Programs In C)

#include <stdio.h>

int main(void) {
  char name[] = "Harry Potter";

  printf("%c", *name);     // Output: H
  printf("%c", *(name+1));   // Output: a
  printf("%c", *(name+7));   // Output: o

  char *namePtr;

  namePtr = name;
  printf("%c", *namePtr);     // Output: H
  printf("%c", *(namePtr+1));   // Output: a
  printf("%c", *(namePtr+7));   // Output: o
}

Functions for Strings Frequently Used(String Programs In C)

  • strlen() – calculates the length of a string
  • strcpy() – copies a string to another
  • strcmp() – compares two strings
  • strcat() – concatenates two strings

Leave a Reply