E-learning

Computer-Based Training (CBT) or Internet-Based Training (IBT) or Web-Based Training (WBT) courses at BengalStudents website

Hiding Data

Hiding Data

To solve a complex problem in practice, the programmer normally breaks the problem into smaller pieces and deals with each piece of the problem by writing one or two functions (or routines). Then, all the functions are put together to form a complete program that can be used to solve the complex problem.

Question and Answer

Question and Answer

Q What is a string? How do you know its length?

A In C, a string is a character array terminated by a null character. Whenever a null character is encountered in a string, functions, such as puts() or strcpy(), will stop printing or copying the next character.

The C function strlen() can be used to measure the length of a string. If it is successful, the strlen() function returns the total number of bytes taken by the string; however, the null character in the string is not counted.

Reading and Writing Strings

Reading and Writing Strings

Now let’s focus on how to read or write strings with the standard input and output streams—that is, stdin and stdout. In C, there are several functions you can use to deal with string reading or writing. The following subsections introduce some of the functions.

The gets() and puts() Functions

The gets() function can be used to read characters from the standard input stream.

The syntax for the gets() function is

Copying Strings with strcpy()

Copying Strings with strcpy()

If you want to copy a string from one array to another, you can copy each item of the first array to the corresponding element in the second array, or you can simply call the C function strcpy() to do the job for you.

The syntax for the strcpy() function is

#include
char *strcpy(char *dest, const char *src);

How Long Is a String?

How Long Is a String?

Sometimes, you need to know how many bytes are taken by a string. In C, you can use a function called strlen() to measure the length of a string.
The strlen() Function

Let’s have a look at the syntax of the strlen() function.

The syntax for the strlen() function is

#include
size_t strlen(const char *s);

Declaring Strings

Declaring Strings

This section teaches you how to declare and initialize strings, as well as the difference between string constants and character constants. First, let’s review the definition of a string.

What Is a String?

As introduced in Hour 12, “Storing Similar Data Items,” a string is a character array terminated by a null character (\0).

For instance, a character array, array_ch, declared in the following statement, is considered a character string: