C Strings - George Washington University

C Strings

1. Objective......................................................................2 2. Introduction..................................................................2 3. String Declaration & Initialization...............................2 4. C Built-in String Function ...........................................5 5. Questions/Practice .....................................................13

Abdelghani Bellaachia, CSCI 1121

Page: 1

1. Objective

What is a string? How do you declare and initialize a string? How can you use a string? Manipulating Strings in C String Examples String Practice

2. Introduction

Sequence of zero or more characters, terminated by NUL (literally, the integer value 0)

Every string is terminated by NUL and NUL is not part of the string.

3.String Declaration & Initialization

A string in C is nothing but an array of type char Two ways to declare a variable that will hold a

string of characters: o Using arrays:

char mystr[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

Abdelghani Bellaachia, CSCI 1121

Page: 2

o Using a string of characters:

char mystr [] = "Hello";

H E L L O \0

Printing Strings: o Can print an entire string using printf and %s format specification o Can print individual elements of a string by indexing and using %c format specification

Example:

//gcc 5.4.0 #include int main(void) {

char mystr1[] = "Fox Music!"; char mystr2[10] = "Fox Music!"; char mystr3[4];

printf("mystr1 = %s\n", mystr1);

for (int i=0; i ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download