This chapter focuses on string operations, including copy strings, copy strings, compare strings, strings, right alignment, delete spaces before and after the string, convert strings, and so on. The C language provides a number of standard library functions that use to process strings, which will introduce some of the functions. When writing a C program, you often use the skills of processing strings. The examples provided in this chapter will help you quickly learn how many common functions, where many examples can effectively help you save the program.
6.1 String copy (strcpy) and memory copy (MEMCPY) What is the case? Which case is it suitable for use?
The strcpy () function can only copy the string. The strcpy () function copies each byte of the source string into the directory string while encountering the NULL character at the end of the string (
When it is deleted, it will end the copy. The Memcpy () function can copy any type of data. Because not all data ends with NULL characters, you have to specify the number of bytes to copy for the memcpy () function. When copying a string, a strcpy () function is usually used; when copying other data (e.g., structures), the Memcpy () function is usually used. The following is an example of using the strcpy () function and the memcpy () function: #include
6. 2 How to delete the spaces of the string tail? The C language does not provide a standard library function that can delete the string tail space, but it is very convenient to write such a function. Please see: #include
). * / While (n> 0) / * make Sure We don't go out of hounds.. * / {If (* (STR N) 1 = ') / * if We Find a nonsecharacter: * / {* (STR N 1) = '
'; / * Put the null character at one character past our current position. * / Break; / * Break out of the loop. * /} Else / * Otherwise, Keep Moving Backward., KEEP moving backward in the string. * /. N--; } Return Str; / * Return a Pointer to the string * /}
In the above example, RTRIM () is a function written by the user, which can delete the space of the string tail. Function RTRIM () starts back to each character from the character before the NULL character in the string, and when you encounter the first character that is not a space, replace the characters behind the character to NULL characters. Because the NULL character is the end flag of the string in the C language, the function RTRIM () actually deletes all spaces of the string tail. See: 6.3 How to delete a space of the character string? 6.5 How to print a string into a designation length? 6.3 How to delete the space of the character string? C language does not provide a string The standard library function of the head space, however, it is very convenient to write such a function. Please see the following example; #include
Void main (void); char * ltrim (char *); char * RTRIM (char *); void main (void) {char * lead_str = "this string has letting space in it."; / * Show the status of The string before calling the itrim () function. * / printf ("Before Calling itrim (), Lead-Str is '% s' / n", lead_str); Printf ("AND HAS A Length OF% D. / n" Strlen (lead_str)); / * Call the itrim () function to remove the leading blanks. * /. iTrim (lead_str); / * show the status of the string after calling the itrim () function. * / prinft (" After Calling itrim (), Lead_STR IS '% S' / N ", Lead_STR); Print (" AND HAS A Length of% D. / N ', Strlen (Lead-Str));} / * the itrim () Function Removes Leading Spaces from a string. * / char * LTRIM (CHAR * STR) {Strrev (STR); / * Call strrevo to reverse the string. * / RTRIM (STR)). / * Call RTRIMO to Remvoe the "Trailing "spaces. * / strrev (str); / * restore the string's Original Order. * / Return Str; / * Return a Pointer to the String. * / } / * The RTRIM () Function Removes Trailing Spaces from a string. * / Char * RTRIM (Char * Str) {INT N = Strlen (Str) -L; / * Start at The Character Before The Null Character
). * / While (n> 0) / * make Sure we don't go out of bounds ... * /. {If (* (STR N)! = ') IF We Find a nonse character: * / {* (STR N 1) = ''; / * put the null character at one character past our current position. * / Break; j / * break out of the loop. * /} Else / * Otherwise, Keep Moving backward in the string. * / n -;} Return Str; / * Return a Pointer to the string. * /} In the above example, the operation of the deleted string header space is done by the LTRIM () function written by the user, the function calls the RTRIM () function and the standard C library function in the example of • 6.2. Strrev (). The LTRIM () function first calls the strRev () function to reverse the string once, then call the RTRIM () function to delete the space of the string tail, and finally call the strRev () function to reverse the string once, the result is actually deleted Original string of spaces.
See: 6.2 How to delete the spaces of the string tail? 6.5 How to print a string into a designated length?
6.4 How to make the string right alignment? The C language does not provide a standard library function that allows the string to right, but it is very convenient to write such a function. Please see the example: #include
Void main (void); char * r just (char * rtrim (char *); void main (void) {char * rjust_str = "this string is not righ-justified."; / * Show the status of The string before calling the rjust () function. * / printf ("Before calling rjust (), rjust_str is '% s' / n.", rjust_str); / * Call the rjusto function to right-justify this string. * / Rjust (rjust_str); / * show the status of the string after calling the rjust () function. * / printf ("after call rjust (), rjust_str is '% s' / n.", rjust_str);} / * the Rjust () Function Right-Justifies a string. * / char * R Just (CHAR * STR) {INT N = Strlen (Str); / * save the original length of the string. * / char * dup_str; dup_str = strDup Str); / * make an exact duplicate of the string. * / RTRIM (DUP_ST); / / * TRIM OFF The trailing spaces. * / / * Call sprintf () to do a virtual "printf" Back Into the Original String. by Passing sprintf () the length of the original string, w e force the output to be the same size as the original, and by default the sprintf () right-justifies the output. The sprintf () function fills the beginning of the string with spaces to make it the same size as the original string. * / sprintf (STR, "% *. * S", n, n, dup_str);
Free (dup-str); / * free the memory taken by the duplicated string. * / return str; / / / * Return a pointer to the string. * /}
/ * The RTRIM () Function Removes Trailing Spaces from a string. * / Char * RTRIM (CHAR * STR) {INT N = Strlen (Str) -L; / * Start at the character before the null character (
). * / While (n> 0) / * make Sure We don't go out of bounds ... * / {if (* (STR N)! = ') / * If We Find a nonse character: * / {* (STR N 1) = ''; (/ * put the null character at One Character Pastur Current position. * / Break; / * Break out of the loop. * /} Else / * Otherwise, Keep Moving Backward In the string. * / n-;} Return Str; / * Return a Pointer to the string. * /} In the previous example, the string of the string is completed by the RJUST () function written by the user. This function calls the RTRIM () function and several standard functions in the example of 6.2. Rjust () function The work procedure is shown below: (1) Save the length of the original string to the variable N. This One step is indispensable because the length of the output string and the original string must be the same. (2) Call the standard C library function strDup (), copy the original string to dup_str. The original string needs to have a copy, because Right alignment strings To write into the original string. (3) Call the RTRIM () function, delete the space of the DUP_STR tail. (4) Call the standard C library function sprinf (), write DUP_STR to the original string Since the length of the original string (in the presence n) is passed to the SPRINTF () function, the length of the output string and the original string are forced to be the same. Because the Sprintf () function defaults to align the output string, the output character is output. The head of the string will be added to make it the same length as the original string, and the effect is actually aligned with the original string string. (5) Call the standard library function free (), release by the strDup () function assignment Dynamic memory to DUP_STR.
See: 6.5 How to print a string into a specified length? 6.5 How to print a string into a specified length? If you want to print a set of strings in the form of a table, you need to print the string into a specified length. This can be easily achieved using the printf () function. Look, see: # include
See: 6.4 How to make the string right alignment? 6.6. How to copy a part of the string? Use the standard library function strNCPY (), you can copy a part of a string to another string. The strncpy () function has 3 parameters: the first parameter is a directory string; the second parameter is a source string; the third parameter is an integer, representing the number of characters to be copied from the source string to the target string . The following is an example of a part of a string with strncpy () function: # include
). This is because the strncpy () function does not automatically add the NULL character when copying the string, so you must make sure that the NULL character is added behind the target string, otherwise it will cause some messy characters. See; 6.1 String copy (strcpy) and memory copy (Memcpy) What is the difference? Which of them is suitable for use? 6.9 How to print a part of the string?
6.7 How to convert digital conversion into a string? C language provides several standard library functions, can convert any type (integer, long integer, floating point, etc.) into a string. The following is an example of converting an integer into a string with the ITOA () function: # include
Void main (void); void main (void) {int Num = 100; char STR [25]; ITOA (Num, STR, 10); Printf ("The Number 'Num' IS% D and The String 'STR' IS % s. / n ", num, str);} The ITOA () function has 3 parameters: the first parameter is the number to be converted, the second parameter is the target string of the conversion result, the third The parameter is the base used when transferring numbers. In the above example, the conversion base is 10. The following functions can convert integers to strings: ---------------------------------------- ------------------ Function name ---------------------------------------------------------------------------------------------------- ----------------------------- iTOA () converts the integer value into string ITOA () converts long integer values For string ultoa () converts unsigned long integer values to string ------------------------------- ------------------------- Please note that the above functions are incompatible with the ANSI standard. Methods that convert integers converted to strings and compatible with ANSI standards are to use sprintf () functions, see the example: #include
} You need to use another set of functions when converting floating-point numbers to a string. The following is an example of converting floating-point values to a string with an FCVT () function: # include
Void main (void); void main (void) {Double Num = 12345.678; CHAR * SIR; INT DEC_PL, SIGN, NDIGITS = 3; / * Keep 3 Digits of Precision. * / Str = FCVT (NUM, NDIGITS, & DEC- PL, & Sign); / * Convert the float to a string. * / printf ("Original Number;% F / N", NUM); / * Print The Original Floating-Point Value. * / Printf ("Converted String;% S / N ", STR); / * Print The Converted String's value. * / printf (" Decimal Place:% D / N ", DEC-PI); / * Print The location of the decimal point. * / printf (" SIGN:% D / N ", SIGN); / * Print The Sign. 0 = POSTIVE, 1 = Negative. * /} The FCVT () function and the ITOA () function have a large number of differences. The FCVT () function has 4 parameters: the first parameter is the floating point value to be converted; the second parameter is the number of digits on the right side of the decimal point in the conversion result; the third parameter is a pointer to an integer, which The integer is used to return the position of the decimal point in the conversion result; the fourth parameter is also a pointer to an integer, which is used to return the symbol of the conversion result (0 corresponds to the positive value, 1 corresponds to a negative value). It should be noted that in the conversion result of the FCVT () function, it does not really contain a decimal point. To do this, the FCVT () function returns the location where the decimal point should occupy in the conversion result. In the above example, the result value of the integer variable DEC_PL is 5 because the decimal decimal point should be located behind the 5th in the conversion result. If you ask for a decimal decimal point in the conversion result, you can use the GCVT () function (see below).
The following functions can convert floating-point values to strings: ------------------------------------- ------------------------------------------------ -------------------------------------------------- ------------ ECVT () converts the double precision floating point value into a string, and does not contain decimal decimal point FCVT () in the conversion result to point the number of conversion accuracy, and Yu ECVT. GCVT () converts the double precision floating point value into a string, including decimal decimal points in the conversion result -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------- See: 6. 8 How to convert a string into a number?
6.8 How to convert a string into a digital? C language provides several standard library functions, which can convert a string to any type (integer, long integer, floating point, etc.). The following is an example of converting a string into an integer with an ATOI () function: # include
Void main (void); void main (void) {Int Num; char * str = "100"; Num = ATOI (STR); Printf ("The string 'str' is% s and the number 'Num' IS% D . / n ", str, num);} The ATOI () function has only one parameter, that is, the string to be converted to a number. The return value of the ATOI () function is the integer value of the conversion.
The following functions can be converted to numbers: -------------------------------------------------------------------- -------------------------------- Function name -------------- -------------------------------------------------- ------ ATOF () Converts String to Dual Precision Floating Point Value ATOI () Converting String to Integer Value ATOL () Converts String to Long Integer STRTOD () Targe String conversion is a double-precision floating-point value, and report all remaining digital strtol () that cannot be converted into long values, and reports all remaining digital strtoul () that cannot be converted to unsigned Long integer value and report all remaining numbers that cannot be converted ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ------------------------------------ Transform strings into numbers can cause overflow, if you Using a function such as stroul (), you can check this overflow error. Please see the example: # include
void main (void); void main (void) {char * str = "1234567891011121314151617181920"; unsigned long num; char * leftover; num = strtoul (str, & leftover, 10); printf ( "Original string:% s / n" , STR); Printf ("Converted Number:% 1U / N", NUM); Printf ("Leftover Characters:% S / N", Leftover);} In the above example, the string to convert is too long, beyond The range of values of the unsigned long integer value, so the start will return ulong_max (4294967295) and make it. Char Leftover points to the part of the character caused by overflows in the string; at the same time, the Strtoul () function also assigns the global variable errno to ERANGE to notify the call of the function overflow error. Function StrtOD () and STRTOL () Handling Overflow errors are identical to function start, you can learn more about the three functions from the compiler document. See: 6.7 How to convert numbers to a string?
6.9 How to print some of the string? 6.6 discussed part of how to copy the string, in order to print a part of the string, you can use some of the skills in 6.6, but you should use it now is Printf () function, not a sprintf () function. Please see the example: # include
Void main (void); void main (void) {charr * source_str = "this is the source string"; / * use printfo to print the first 11 characters of source_str. * / printf ("first 11 characters: '% 11. LLS '/ N ", Source_Str); / * Use printf () to print only the last 13 character_Str. * / printf (" Last 13 Characters:'% 13.13 '/ n ", Source_Str (Strlen (Source_Str) - 13));} The printout of the previous example is as follows: first 11 characters: 'this is the' Last 13 Characters: 'source string' In the previous example, when the printf () function is called for the first time, by specifying parameters " % 11.11s ", forcing the printf () function to print only the length of 11 characters, because the length of the source string is greater than 11 characters, so the source string will be cut off, only the first 11 characters are printed. . When the Printf () function is called the second time, it prints the last 13 characters of the source string, and its implementation process is: (1) calculate the length of the Source_Str string with the strlen () function, the strlen (Source_STR). (2) minus the length of Source_Str minus 13 (13 is the number of characters to be printed), draw the number of remaining characters in Source_STR, and pstrlen (Source_STR) -13. (3) Add the address of Strlen (Source_STR) -13 and Source_STR to the pointer to the address of the number 13 characters in the Source_Str; "Source_Str (Strlen (Source_STR) -13). This pointer is the second parameter of the Printf () function. (4) By specifying the parameter "% 13.13s", forcing the printf () function to print only 13 characters, the result is actually the last 13 characters of the print source string. See: 6.1 String copy (strcpy) and memory copy (Memcpy) Is there anything different? Which of them is suitable for use? 6.6 How to copy part of the string?
6.10 How to determine if the two strings are the same? The C language provides several standard library functions, which can compare whether the two strings are the same. The following is an example of comparing strings with strcmp () functions: #include
void main (void); void main (void) {char * STR_1 = "abc"; char * STR_2 = "abc"; char * STR_3 = "abc"; if (str_1, str_2) == 0) Printf "str_1 is equal to str_2. / n"); Else Printf ("str_1 is not equal to str_2. / n"); IF (str_1, str_3) == 0) Printf ("str_1 is equal to str_3./ N "); Else Printf (" STR_1 IS Not Equalto STR_3./N ");} The printout of the previous example is as follows: STR_1 IS Equal to STR_2. STR_1 IS Not Equal to STR_3. The strcmp () function has two parameters, that is, two strings to be compared. The strcmp () function is compared to the two string case-sensitive and Dictionary (lexicographic) and one of the following values: --------------- ------------------------------------- 回 值 意 -------- -------------------------------------------- <0 first characters Strings less than the second string 0 two strings equal ·> 0 The first string is greater than the second string --------------------- --------------------------- In the above example, when comparing STR_1 (ie "ABC") and STR_2 (ie "ABC" When the STRCMP () function is 0. However, when comparing STR_1 (ie "ABC") and STR_3 (ie, "ABC"), the strcmp () function returns a value greater than 0 because the ASCII sequence string "ABC" is smaller than "ABC". The strcmp () function has many variants, and their basic functions are the same, which are compared to two strings, but other places are slightly different.
The following table lists some functions similar to the strcmp () function provided by the C language: ------------------------------- ----------------------------------------------- -------------------------------------------------- ---- Strcmp () Samples STRCMPI () on two strings STRCMPI () STRICMP () with strcmpi () strncmp () is part of the two strings. Samples STRNICMP () in case Strnicmp () is not sensitive to part of the two strings ------------------------- -------------------------------------- In the previous example, if you use the strcmpi () function Instead of the strcmp () function, the program will consider "ABC" equal to "ABC". See: 6.1 String Copy (STRCPY) and memory copy (Memcpy) What is the difference? Which of them is suitable for use?