495 C Language questions you must know, learning experience Five

Source: Internet
Author: User
Tags printable characters strtok

This article is the fifth in a series of 495 C-language questions that you need to know, mainly to understand the character and string related things, but also to involve memory-related knowledge.

In general, the processing of strings and characters is a regular in programming languages, and in C we are given very good flexibility, but at the same time the characters become the most secretive processing unit.
In the contents of the pointer, I basically explained the difference between the string and the character array, so I won't repeat it here.

We know that the English translation of the characters is character, which is why the character type is char, and we use the single quotation mark ' to mark a character and use the double quotation mark "" to mark the string. In fact, there is no built-in string type in the C language, so it is customary to use an array of characters ending with ' \ s ' to represent a string, or to appear as a string constant. And again, the C language does not have a real character type, and the character is represented by its integer value in the machine character set.

Character manipulation

The standard library provides two sets of functions for manipulating individual characters in ctype.h, the first set for character classification, and the second for converting characters.

Character classification

Begins with is to determine what type this character belongs to: Yes returns true

Iscntrl///any control character isspace//blank character: ' Change page ' \f ' newline ' \ n ' carriage return ' \ r ' tab ' \ t ' or vertical tab ' \v ' isdigit//10 decimal any number isxdigit//16 binary any number Islower Lowercase letter Isupper//Capital Letter Isalpha//All letters ISALNUM//All letters and numbers ISPUTCT//punctuation isgraph//Graphic symbols isprint//any printable characters

  

Character conversions
int tolower (int ch);//convert to lowercase int toupper (int ch);//Convert to uppercase

  

String manipulation

In order to manipulate strings in the C language, the standard library declares some functions in the header file string.h. such as the concatenation of strings, copy, find, and so on. For example, there will always be interviews to examine the wording of strcpy, which is really a nasty thing. Since the C-style string is a char-type array of characters, we can manipulate the characters in the string by pointers and array subscripts.

String length

Maybe you think the string length calculation is not worth mentioning, strlen is the simplest string-handling function you've ever written.
If you think the following writing is your work, please note:

int Mystrlen (char *str) {int lenght =0;while (*str++!= ') Lenght++;return lenght;}

  

At first glance, the program runs correctly and there are no bugs, but if the total score is 100, the function can only get 50 points. The veteran will not look, the heart knows, the novice can be corrected from the following aspects:

    1. The return value type of the program
    2. Parameter type qualification of the program
    3. Non-null judgment of the entry parameter
    4. Do not attempt to write a mystrlen but call the standard strlen function directly

The following optimizations can be made:

#include <stddef.h>size_t mystrlen (char const*str) {int lenght =0;  while (*str++!=') Lenght+ +; return lenght;}

Note, size_t is related to the environment, generally the unsigned int type, the in parameter is null not checked, is to illustrate that such a function should be called before, let the caller show that the argument is not empty.

String copy
Char *strcpy (char *dst, Char const * src); Char *strncpy (char *dst,char const * SRC, size_t len);

It is clear that strcpy copies the SRC string contents to DST, while strncpy copies only Len bytes, with the following notes:

    1. The caller must ensure that the DST memory interval size is reasonable to avoid overflow when copying SRC, and strcpy itself is not checked.
    2. After a normal call, strcpy can automatically add ' \ ' at the end of the copy without adding it manually, but strncpy otherwise, if the SRC length is longer than the parameter Len, the caller is required to manually add '/'. This is a point to note.
Concatenation of strings
Char *strcat (char *dst,char const *src); Char *strncat (char *dst,char const *src,size_t len);

Strcat the contents of SRC to the back of the DST, which is a concatenated action of a string, while Strncat is the first Len character of the SRC connection to DST. However, unlike strncpy, it guarantees that the new string will be added to the end after it is finished.

The return values of the string copy and the concatenation function are char* to call these functions in order to be nested. In fact, the return value is frequently ignored.

Comparison of strings
int Const *s1,char const* S2); int strncmp (charconst *s1,char const* s2,size_t len);

A comparison of two strings returns 0, which is greater than the latter, which returns a value greater than 0, or returns a value less than 0.
strcmp compare all, while strncmp compares the first Len characters of both.

String Lookup
    • Find a character,
Char *strchr (charconst *SRC,int  ch); Char *strrchr (charconst *SRC,int ch);

STRCHR the first occurrence of the CH character from SRC, the pointer is returned
The STRRCHR is the reverse lookup, or the last occurrence of the position.

    • Find any few characters
Char *strpbrk (charconst *str,charConst* group);

This function finds the first occurrence of any one of the group's positions in STR,

    • Find a substring
Char *strstr (char const * S1,char const*s2);

  

This function finds the starting position of the first occurrence of the entire S2 in S1 and returns a pointer to that location.

Note: The standard library does not provide the prototype of STRRPBRK and STRRSTR, but we can implement one ourselves,

    • Find the prefix of a string
size_t strspn (char const* str,char const*group); size_t strcspn (char const* str,char const*group);

  

STRSPN returns the sum of the number of characters of any character in the Str start Match Group
STRCSPN is the sum of the number of characters that are different from any character in the group, with the meaning of complement.
Look directly at the code to better understand:

#include <string.h>char* str ="123123,helloWorld";p rintf (  "%d\n", (int) strspn (str,"123,")) ;p rintf ("%d\n", (int) strcspn (str,""));

Output results

    1. 7
    2. 12

Strspn finds the sum of the preceding all 123 and, 7, and STRCSPN finds the number of characters that are not spaces in the prefix, 12, so, the use of these two functions, you should be clear.

    • Find tags
      A string often contains several separate parts that are separated from each other, and each time you have to extract them from the string in order to process the various parts, this task is a function implemented by Strtok.
Char *strtok (char *str,char const* Sep);

  

The Sep parameter is a string that defines the character set used as a delimiter. The first argument is a string that contains 0 or more tags delimited by the sep character, Strtok finds the next tag of STR, ends it with nul, and returns a pointer to the tag. Warning: Strtok will change the string it looks for, so you know how to do it.

If the first argument of the Strtok function is not NULL, the function will find the first token of the string, Strtok will also save its position in the string, if the first parameter of the Strtok function is null, The function starts at this position in the same string, looks for the next tag as before, returns a null pointer if there are no more such tokens in the string, and, in typical cases, passes a pointer to the string to the strtok the first time it is called. The function is then called repeatedly (the first parameter is NULL) until it returns a null.

Remember: Strtok has a "memory" function, so do not attempt to parse two strings at the same time. Similarly, because strtok will change the incoming string itself, we should not pass in string constants, so please copy one to use.
Look at the code:

Char str[]="123,45,67;6,23;2;31"; // If you change it here, Char *str will crash . Static char*sep =",; " ; Char* token = NULL;  for (token == = Strtok (null,sep)) printf ("", token);

The output is as you wish;

Memory operations

We know that the C string must end with ' + ', so it is not uncommon for non-string processing to contain 0 of cases, so we need to manipulate the memory directly to ensure that ' \ ' is also being processed.

void* MEMCPY (void*DST,void Const*src,size_t lenght);void* Memmove (void*DST,void Const*src,size_t lenght);void* MEMCMP (void Const*a,void Const*b,size_t lenght);void* MEMCHR (void Const*a,intch,size_t lenght);void* Memset (voidAintch,size_t lenght);

Because the memory operation does not have an end flag, the length (in bytes) must be indicated in the last parameter. These functions have the same meaning as a function with the same suffix as the string, so don't repeat them.

495 C Language questions you must know, learning experience Five

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.