Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Strings:

Absolutely! Let's talk about strings in C using simple language:

What's a String?

A string in C is a sequence of characters, like words or sentences in English. Just as you can manipulate words and sentences, you can manipulate strings in C.

Declaring and Initializing Strings:

To use strings in C, you declare them as arrays of characters. Then, you can either initialize them right away or assign values later.

// Declaring and initializing a string
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; // '\0' represents the end of the string

Or you can declare and initialize a string like this:

char greeting[] = "Hello"; // C automatically calculates the size of the array

Accessing Characters in a String:

char firstChar = greeting[0]; // Gets the first character 'H'

Printing a String:

You can print a string using the printf() function from the stdio.h library.

printf("%s\n", greeting); // Prints the string "Hello"

Example:

Let's say you have a program that greets the user with their name:

#include <stdio.h>

int main() {
char name[20]; // Declare a string to hold the name (up to 19 characters + '\0')

// Ask the user for their name
printf("What's your name? ");
scanf("%s", name); // Read the user's input and store it in the 'name' variable

// Greet the user
printf("Hello, %s! Welcome to the program.\n", name);

return 0;
}

In this example:



Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java