Tutorial - C Strings and String functions - Part 1


Submit solution

Points: 1 (partial)
Time limit: 2.0s
Memory limit: 64M

Author:
Problem type
Allowed languages
C

Tutorial

Compiled from multiple sources on the internet.

Since this is a tutorial, there is no submission data for this. Please use the IDE for practice.

C – Strings and String functions

String is an array of characters. In this guide, we learn how to declare strings, how to work with strings in C programming and how to use the pre-defined string handling functions.

We will see how to compare two strings, concatenate strings, copy one string to another & perform various string manipulation operations. We can perform such operations using the pre-defined functions of “string.h” header file. In order to use these string functions you must include string.h file in your C program.

1. String Declaration

Method 1:

char address[]={'I', 'N', 'D', 'I', 'A', '\0'};

Method 2: The above string can also be defined as –

char address[]="INDIA";

Method 3:

char str[50] = "ThisIsC";

Method 4:

char str[15] = {'T','h','i','s','I','s','C','\0'};

In the Method 2 and 3 declaration, NULL character (\0) will automatically be inserted at the end of the string.

What is NULL Char “\0”?

'\0' represents the end of the string. It is also referred as String terminator & Null Character.

The image below gives an idea of how strings are represented in the computer memory.

String Representation in C

2. Read & write Strings in C using Printf() and Scanf() functions

#include <stdio.h>
#include <string.h>
int main()
{
    /* String Declaration*/
    char name[20];

    printf("Enter your name:");

    /* I am reading the input string and storing it in nickname
     * Array name alone works as a base address of array so
     * we can use nickname instead of &nickname here
     * The printf given is only for representation, 
     * you do not need to use it on HPOJ. You can get user input without printing
     */
    scanf("%s", name);

    /*Displaying String*/
    printf("%s",nickname);

    return 0;
}

Output:

Enter your name: Name1

Name1

Note: %s format specifier is used for strings input/output

3. Read & Write Strings in C using gets() and puts() functions

#include <stdio.h>
#include <string.h>
int main()
{
    /* String Declaration*/
    char nickname[20];

    /* Console display using puts */
    puts("Enter your Name:");

    /*Input using gets*/
    gets(nickname);

    puts(nickname);

    return 0;
}

Try getting and manipulating strings using the IDE.

Continued in Part 2


Comments

There are no comments at the moment.