Common C language string operation functions in Linux

Source: Internet
Author: User
Tags integer numbers month name

Stroul,
Strdup
Snprintf ()
Atio
 
Common string operation functions in C
# Include <string. h>
 
Size_t strlen (const char * s) measures the actual length of String Length S.
For example, if s [20] = "ABC", the result of strlen (s) is 3 rather than 20. This is the actual length.
 
Char * strcat (const char * S1, const * S2) connects string S2 to the end of S1. Start from/0 of S1.
 
Int strcmp (const * S1, const * S2) compares S1 and S2.
S1 = S2 return value = 0
S1 <S2 returns to <0
Return value> 0 when S1> S2
 
Char * strchr (const char * s, char C); returns the pointer to the first occurrence of C in S. If C does not exist in S, null is returned.
 
Char * strrchr (const char * s, char C); returns the pointer to the last occurrence of C in S. If no value exists, 0 is returned.
 
Char * strstr (const char * haystack, const char * needle); returns the pointer to the first position where the needle string appears in the haystack (null is not compared with the terminator ). If not found, null is returned.
 
 
Comparison of limited length, copying and appending Functions
Int strncmp (char * S1, const char * S2, size_t N); (these are all for the first n characters of the string)
 
Char * strncpy (char * DEST, const char * SRC, size_t N );
 
Char * strncat (char * DEST, const char * SRC, size_t N );
 
Char * strdup (char * s) returns a pointer to the copied string. the required space is allocated by malloc () and free space is required.
 
Int atoi (const char * nptr); converts a string to an integer.
Atoi () scans the nptr parameter string and skips the leading space until it encounters a number or a plus or minus sign, when a non-digit or non-string ends ('/0 ')
In fact, Ato is a family of functions that convert characters into numbers, atof and atol: they convert strings into floating-point and long integer numbers respectively.
 
 
Unsigned long int stroul (const char * nptr, char ** endptr, int base );
Stroul () converts the string nptr to the unsigned long integer number according to the base-specified hexadecimal (10 represents the hexadecimal, 18 represents the hexadecimal, the base range is 2 ~ 36, or 0. When the base value is 0, the conversion is made using 10. When a character starting with '0x 'is encountered, the conversion is made using 16. At the beginning, stroul () will scan the nptr parameter string, skip the leading space string, and start conversion only when a number or plus or minus sign is encountered, end the conversion when a non-number or string ends '/0' and return the result. If the endptr parameter is not null, the string pointer of the nptr that is terminated due to an exception is returned by the endptr.
Stroul () returns the converted long integer; otherwise, returns erange and stores the error code in errno.
The conversion string specified by erange exceeds the valid value.
 
Int snprintf (char * restrict Buf, size_t N, const char * restrict format ,...)
Snprintf () can copy up to n-1 characters from the source string format to the target string Buf, and then add a '/0 '. if the target string is N, it will not overflow.
If snprintf () is successful, the number of characters stored in the array is returned. If an error occurs, a negative value is returned.
Routine:

# Include <stdio. h> <br/> # include <stdlib. h> </P> <p> int main (INT argc, char ** argv) <br/> {<br/> char STR [5]; <br/> char S = "Linux is powerful! "<Br/> snprintf (STR, 5, S); <br/> printf (" str = % s ", STR); <br/>}

Running result

STR = linu

 

Int sprintf (char * Buf, char * format, arg_list );

Sprintf ()
Is a powerful function. With printf (char
* Format, arg_list) functions are similar. However, printf () Outputs formatted characters to the screen, while sprintf () places formatted characters
Buf. This function provides great convenience for operating the buffer Buf and formatting its content.

For example:

# Include <stdio. h> <br/> # include <string. h> </P> <p> char * Buf; <br/> char * A = "Linux"; <br/> char * B = "is "; <br/> char * c = "powerful"; <br/> sprintf (BUF, "Hello: % S % s", A, B, C ); <br/> printf ("% s", Buf );

Output result:

Hello: Linux is powerful

TIPS:

Strlen () and strcat () are two time-consuming operations. It should be used less in programs.

In the definition of char type, if the char parameter is not modified after being passed in, you should add const

For example, a (const char * s); the content of the S string is not modified after it is passed in. Add Const.

 

Relationship between const char * P and char const * P

It can be distinguished by pronunciation.

Const char * P

P is point to const char;

Char const * P

P is a const point to Char;

# Include <stdio. h> int Rename (const char * oldfname, const char * newfname); used to change the file name

 

Sscanf ()-read data that matches the specified format from a string.
Function prototype:
Int sscanf (string STR, string FMT, mixed var1, mixed var2 ...);
Int scanf (const char * Format [, argument]...);
Note:
Similar to scanf, sscanf is used for input, but the latter uses the screen (stdin) as the input source, and the former uses a fixed string as the input source.
The format can be one or more {% [*] [width] [{H | L | i64 | L}] type | ''| '/T' | '/ n' | non-% sign}

1. Common usage.
Char Buf [512] =;
Sscanf ("123456", "% s", Buf );
Printf ("% s/n", Buf );
Result: 123456
2. Take a string of the specified length. In the following example, a string with a maximum length of 4 bytes is obtained.
Sscanf ("123456", "% 4 s", Buf );
Printf ("% s/n", Buf );
Result: 1234
3. Obtain the string of the specified character. For example, in the following example, the string is obtained when a space is encountered.
Sscanf ("123456 abcdedf", "% [^]", Buf );
Printf ("% s/n", Buf );
Result: 123456
4. Take a string that only contains the specified character set. For example, in the following example, take a string that only contains 1 to 9 letters and lowercase letters.
Sscanf ("123456 abcdedfbcdef", "% [1-9a-z]", Buf );
Printf ("% s/n", Buf );
Result: 123456 abcdedf
5. Obtain the string of the specified character set. For example, in the following example, a string with uppercase letters is used.
Sscanf ("123456 abcdedfbcdef", "% [^ A-Z]", Buf );
Printf ("% s/n", Buf );
Result: 123456 abcdedf
6. Given a string iios/12ddwdff @ 122, get the string between/and @ and filter out "iios/" first, then, send a string of content other than '@' to the Buf.
Sscanf ("iios/12ddwdff @ 122", "% * [^/]/% [^ @]", Buf );
Printf ("% s/n", Buf );
Result: 12 ddwdff.
7. Given a string "Hello, world", only world is retained. (Note: There is a space after)
Sscanf ("Hello, world", "% * S % s", Buf );
Printf ("% s/n", Buf );
Result: World
% * S indicates that the first matching % s is filtered out, that is, hello is filtered out.
If there is no space, the result is null.
Sscanf is similar to a regular expression, but does not have a strong regular expression. Therefore, we recommend that you use a regular expression for complex string processing.
//-------------------------------------------------------
Sscanf, indicating formatting input from string
In STR, input a number to X, which is 32700.
A long time ago, I thought c didn't have its own split string function. Later I found sscanf. For a long time, I thought sscanf could only define strings with spaces. Now I found that I was wrong.
Sscanf is a runtime function. Its prototype is simple:
Int sscanf (
Const char * buffer,
Const char * Format [,
Argument]...
);
Its powerful functions are reflected in its support for format.
I used to separate a string like this 2006: 03: 18:
Int A, B, C;
Sscanf ("200:0:18", "% d: % d", A, B, C );
And-2006: 04: 18:
Char sztime1 [16] = "", sztime2 [16] = "";
Sscanf ("2006:0:18-2006:04:18", "% s-% s", sztime1, sztime2 );
But later, I needed to handle
The space on both sides of '-' is canceled, but the % s definition of the string is broken.
I need to re-design a function to handle this situation? This is not complicated, but in order to make all the Code have a uniform style, I need to change many places and replace the existing sscanf with my own split function. I thought I must do this and fell asleep with a strong dissatisfaction with sscanf. I woke up and found that I didn't have.
The format-type has a type field such as %. If the string to be read is not separated by spaces, you can use % [].
% [] Is similar to a regular expression. [A-Z] indicates that all characters of A-Z are read, and [^ A-Z] indicates that all characters except a-Z are read.
That's why the problem was solved:
Sscanf ("2006:0:18-2006:04:18", "% [0-9,:]-% [0-9,:]", sztime1, sztime2 );

 

Strftime ()

The strftime () function Format the time.
We can use the strftime () function to format the time as we want. Its prototype is as follows:
Size_t strftime (
Char * strdest,
Size_t maxsize,
Const char * format,
Const struct TM * timeptr
);
You can place the time information stored in timeptr in the strdest string based on the format command in the string to which the strdest points. A maximum of maxsize characters can be stored in strdest. This function returns the number of characters placed in the string pointing to strdest.
The strftime () function is similar to sprintf (): recognizes the command set starting with the percent sign (%), and formats the output result in a string. The formatting command specifies the exact representation of various date and time information in strdest. Other characters in the format string are put into the string as they are. Format Commands are listed below, which are case sensitive.
% A abbreviation of the day of the week
% A full name of the day of the week
Abbreviation of % B month
% B full name
% C standard date time string
The last two digits of the Year % C
% D indicates the day of the month in decimal format.
% D month/day/year
% E indicates the day of the month in decimal format in the two-character field
% F-month-day
The last two digits of the Year % G. The year is based on the week.
% G year, based on the week Year
% H abbreviated month name
% H in 24-hour format
% I 12-hour
% J indicates the day of the year in decimal format.
Month in % m decimal format
% M decimal number of minutes
% N new line operator
% P equivalent display of local am or PM
% R 12 hours
% R display hour and minute: hh: mm
% S decimal seconds

(To be continued)

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.