How to process strings in C Language

Source: Internet
Author: User
Tags date1

Http://www.cnblogs.com/robin-ty/archive/2010/09/03/1817294.html

 

Communication Link"

-- Modern method of C language programming

 

I have written more java code and love the string class. Unfortunately, the typical C language does not exist... Recently, in the process of program development, I found that the processing of C language strings is very fuzzy. I will use arrays, pointers, and strings. h later... So I decided to summarize the processing of strings in the C language, one as a note, and the other as a technical exchange.

    1. String Literal (A String constant, called in the C standard,String Literal)
      How to store string literalIn essence, the C language treats the string literal as a character array. When the C language compiler encounters a string literal with a length of N in a program, it allocates a memory space with a length of N + 1 to the string literal, and adds an additional character at the end --NULL Character(\ 0 ).
      String Literal operations
      Generally, the string literal can be used wherever the char * pointer is allowed in any C language. For example:

      Char * P; P = "ABC ";

      This assignment operation does not copy the characters in "ABC", but simply points P to the first character of the string.

    2. Some programming languages of string variables provide special string types for declaring strings. The C language adopts different methods: as long as the string ends with an empty string, any one-dimensional character array can be used to store strings. If you write your own string processing functions, be sure to correctly process null characters. Assume that the variable is used to store strings of up to 80 characters. Since a string requires null characters at the end, the variable to be declared is an array containing 81 characters. # Define str_len 80
      /* Common usage */Char STR [str_len + 1];

      This method is commonly used by C programmers.
      Initialize string variables

      Char date1 [8] = "June 14 ";

      Date1: | j | u | n | E | 1 | 4 | \ 0 |

      Char date2 [9] = "June 14 ";

      Date2: | j | u | n | E | 1 | 4 | \ 0 | \ 0 | in general, this behavior is consistent with the C language method for Array initialization. The length of a string variable can be ignored. In this case, the compiler automatically calculates the length:

      Char date3 [] = "June 14 ";

      The compiler allocates 8 characters for date3.Character array and character pointerTo compare the two declarations in the statement:

      Char date [] = "June 14 ";

      It declares that date is an array of characters. Similar to this statement, the following statement is used:

      Char * Date = "June 14 ";

      It declares that date is a pointer to the string literal. [Note] the preceding two dates cannot be mistakenly considered interchangeable. There is a significant difference between the two: (1) when declared as an array, you can modify the characters stored in date just like any array element. When declared as a pointer, date points to the string literal. (2) When declared as an array, date is the array name. When declared as a pointer, date is a variable, which can point to other strings during program execution.   If you want to modify a string, you need to create a character array to store the string. In this case, it is not enough to declare the pointer variable. The following statement assigns sufficient memory space to the pointer variable:

      Char*P;

      Unfortunately, it does not allocate space for strings. Before using P as a string, you must point P to the string array. One possibility is to point P to an existing string variable:

      CharSTR [str_len+1],*P; P=STR;

      Now P points to the first character of STR, so P can be used as a string.

 

3. Read and Write strings

 

3.1 Use the printf and puts functions to write strings

% S allows the printf function to write strings. For example:

Char STR [] = "Are we having fun yet? "; Printf (" value of STR: % s \ n ", STR );

If only part of the string is displayed, you can use %.PS. HerePIs the number of characters to display. Statement

Printf ("%. 6s \ n", STR );

Will display

Are we

The C function library also provides the puts function.

Puts (STR );

  

3.2 use the scanf and gets functions to read strings

In scanf function calls, you do not need to add the operator & before Str &. Because STR is an array name, the compiler automatically treats it as a pointer. During the call, the scanf function skips the white space characters, then reads the characters, and stores the characters to STR, until the white space characters are encountered. The scanf function always stores an empty character at the end of the string. Using the scanf function to read strings will never contain white spaces. Therefore, the scanf function usually does not read a whole line of input. Line breaks will stop the scanf function reading, and space characters or tabs will also produce the same effect. See the following example:

# Include <stdio. h>
# Define str_len 80
Int main () {char STR [str_len + 1]; printf ("input a string:"); scanf ("% s", STR); printf ("string inputed is: % s \ n ", STR); return0 ;}

 

The running result is as follows:

Input a string: This is a string is: this

You can use the gets function to read a whole line of input each time. Similar to the scanf function, the gets function puts the characters read into the array and stores an empty character. However, the gets function is somewhat different from the scanf function in other aspects:

 

(1) The gets function does not skip the blank characters before starting to read the string (the scanf function will skip ).

(2) The gets function will continue to read until the line break is found (the scanf function will stop at any blank character ).

In addition, the gets function ignores the line break instead of storing it in the array. It replaces the line break with null characters.

 

3.3 read strings one by one

Because scanf and gets functions are risky and not flexible enough, C programmers often write their own input functions. Each time a character is used to read a string. The read_line () function for reading strings is as follows ():

Int read_line (char STRP [], int N) {char ch; int I = 0;
While (CH = getchar ())! = '\ N') if (I <n) STR [I ++] = CH; STR [I] =' \ 0';/* terminates string */return I; /* number of characters stored */}

Before return, the read_line function places an empty character at the end of the string. Just like scanf and gets functions, standard functions automatically place an empty string at the end of the input string. However, if you write the input function yourself, you must consider this.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.