C-language string processing functions, string functions

Source: Internet
Author: User

C-language string processing functions, string functions
C language string processing function http://blog.csdn.net/ruizeng88/article/details/6677736

1. String comparison

Int strcmp (const char * s1, const char * s2 );

When comparing the sizes of two strings (case-insensitive), the return value is learned: If s1 is less than s2, a number smaller than 0 is returned. If s1 is greater than s2, a number greater than 0 is returned, if they are equal, 0 is returned. The return value is the difference between the first unequal ascii code of two strings. The implementation is as follows:

 

[Cpp]View plaincopyprint?
  1. Int my_strcmp (const char * s1, const char * s2 ){
  2. // Important! Validate arguments first!
  3. Assert (NULL! = S1 & NULL! = S2 );
  4. While (* s1! = '\ 0' & * s2! = '\ 0' & * s1 = * s2 ){
  5. S1 ++;
  6. S2 ++;
  7. }
  8. Return * s1-* s2;
  9. }
int my_strcmp(const char *s1, const char *s2){//important! validate arguments first!assert(NULL !=s1 && NULL != s2);while(*s1 != '\0' && *s2 != '\0' && *s1==*s2){s1++;s2++;}return *s1 - *s2;}

Note that the function starts parameter check again to prevent runtime errors when the input parameter is NULL.

Strcmp is the most commonly used string comparison function. The general usage is if (! Strcmp (s1, s2 )){...}. If you do not compare the entire string but only compare a specified number of strings, you can use the following function:

Int strncmp (const char * s1, const char * s2, size_t n );

The usage and return values are similar to those of strcmp, which compares the first n characters of a given string or ends with any character string. The implementation is as follows:

 

[Cpp]View plaincopyprint?
  1. Int my_strncmp (const char * s1, const char * s2, size_t n ){
  2. // Important! Validate arguments first!
  3. Assert (NULL! = S1 & NULL! = S2 );
  4. If (n = 0)
  5. Return 0;
  6. Size_t cnt = 1;
  7. While (* s1! = '\ 0' & * s2! = '\ 0' & * s1 = * s2 & cnt <n ){
  8. S1 ++;
  9. S2 ++;
  10. Cnt ++;
  11. }
  12. Return * s1-* s2;
  13. }
int my_strncmp(const char *s1, const char *s2, size_t n){//important! validate arguments first!assert(NULL!=s1 && NULL!=s2);if(n == 0)return 0;size_t cnt = 1;while(*s1 != '\0' && *s2 != '\0' && *s1==*s2 && cnt < n){s1++;s2++;cnt++;}return *s1 - *s2;}
In addition to parameter check, pay attention to the special case where n = 0. Here we will always return 0 if n = 0.

 

 

There are other string comparison functions with special requirements, such:

Stricmp, memcmp, memicmp, and so on. If I is added, Case sensitivity is ignored. If mem is used, a memory interval is compared.

2. string SEARCH

The simplest is to search for character strings:

Char * strchr (const char * s, int c );

As for the reason why the parameter is int, we will not discuss the issues left over from history here. The function returns the pointer to the first c position found in s. Note that '\ 0' at the end of the string can also be searched. The implementation is as follows:

[Cpp]View plaincopyprint?
  1. Char * my_strchr (const char * s, int n ){
  2. Assert (s! = NULL );
  3. Char c = (char) n;
  4. Do {
  5. If (* s = c)
  6. Return (char *) s;
  7. } While (* s ++ );
  8. Return NULL;
  9. }
char *my_strchr(const char *s, int n){assert(s != NULL);char c = (char)n;do{if(*s == c)return (char *)s;}while(*s++);return NULL;}
Strstr:

Char * strstr (const char * s1, const char * s2 );

The function returns the position of the first character of s2 in S1. the implementation is as follows:

[Cpp]View plaincopyprint?
  1. Char * my_strstr (const char * s1, const char * s2 ){
  2. Assert (NULL! = S1 & NULL! = S2 );
  3. Size_t len = strlen (s2 );
  4. While (* s1 ){
  5. If (! Strncmp (s1, s2, len ))
  6. Return (char *) s1;
  7. S1 ++;
  8. }
  9. Return NULL;
  10. }
char *my_strstr(const char *s1, const char *s2){assert(NULL!=s1 && NULL!=s2);size_t len = strlen(s2);while(*s1){if(!strncmp(s1,s2,len))return (char *)s1;s1++;}return NULL;}

The c standard library does not define a function similar to strnchr and strnstr that limits the search range. Of course, we can define the function as needed, for example:

[Cpp]View plaincopyprint?
  1. Char * strnstr (const char * s1, const char * s2, size_t n)
  2. {
  3. Const char * p;
  4. Size_t len = strlen (s2 );
  5. If (len = 0 ){
  6. Return (char *) s1;
  7. }
  8. For (p = s1; * p & (p + len <= buffer + n); p ++ ){
  9. If (* p = * token) & (strncmp (p, token, tokenlen) = 0 )){
  10. Return (char *) p;
  11. }
  12. }
  13. Return NULL;
  14. }
char *strnstr(const char* s1, const char* s2, size_t n){  const char* p;  size_t len = strlen(s2);  if (len == 0) {    return (char *)s1;  }  for (p = s1; *p && (p + len<= buffer + n); p++) {    if ((*p == *token) && (strncmp(p, token, tokenlen) == 0)) {      return (char *)p;    }  }  return NULL;}
3. Copy strings

The most common string replication function is strcpy:

Char * strcpy (char * dst, const char * src );

Copy the string ending with NULL indicated by src to the string referred to by dst. src and dst cannot be the same (can be declared by the restrict keyword of c99 ), dst must have enough space to store the copied string.

Note that the return value of the function is a pointer to dst. This is used to facilitate inline statements in the program, such as strlen (strcpy (s, t )).

The function is implemented as follows:

[Cpp]View plaincopyprint?
  1. Char * my_strcpy (char * dst, const char * src ){
  2. Assert (NULL! = Dst & NULL! = Src );
  3. Char * p = dst;
  4. While (* dst ++ = * src ++ )! = '\ 0 ');
  5. Return p;
  6. }
char *my_strcpy(char *dst, const char *src){assert(NULL!=dst && NULL!=src);char *p = dst;while((*dst++ = *src++) != '\0');return p;}

It is dangerous to use strcpy because the function itself does not check whether the space pointed to by dst is sufficient to store the string to be copied, resulting in a potential risk of string overflow. This is also a classic vulnerability that hackers used in the last century. Therefore, in most cases, strncpy is more secure:

[Cpp]View plaincopyprint?
  1. Char * my_strncpy (char * dst, const char * src, size_t n ){
  2. Assert (NULL! = Dst & NULL! = Src );
  3. Char * p = dst;
  4. While (n ){
  5. If (* dst ++ = * src ++) = '\ 0 ')
  6. Break;
  7. N --;
  8. }
  9. Return p;
  10. }
char *my_strncpy(char *dst, const char *src, size_t n){assert(NULL!=dst && NULL!=src);char *p = dst;while(n){if((*dst++ = *src++) == '\0')break;n--;}return p;}

Note that another function strdup:

Char * strdup (const char *);

The difference between this function and strcpy is that the function will apply for memory space to store the copied string, and then return a pointer to the string. Therefore, when using the strdup function, you must note that after using the copied string, use the free function to release the occupied space.

In addition, the memcpy function is similar to strncpy, but does not terminate the copy when NULL is encountered. This function will certainly copy n characters.

 

4. String connection

A string connection connects the header of a string to the end of another string.

Char * strcat (char * s1, const char * s2 );

The function is implemented as follows:

[Cpp]View plaincopyprint?
  1. Char * my_strcat (char * s1, const char * s2 ){
  2. Assert (NULL! = S1 & NULL! = S2 );
  3. Char * p = s1;
  4. While (* s1) s1 ++;
  5. Strcpy (s1, s2 );
  6. Return p;
  7. }
char *my_strcat(char *s1, const char *s2){assert(NULL!=s1 && NULL!=s2);char *p =s1;while(*s1)s1++;strcpy(s1,s2);return p;}

Similarly, strcat is insecure because it also assumes that the buffer zone is sufficient to store the connected strings. Therefore, in most cases, we should use more secure:

Char * strncat (char * s1, const char * s2, size_t n

 

-------------------------------------

 

Classify the information you need and slowly crawl string truncation functions and applications in C Language


/* ===================================================== ============================

For a five-digit a1a2a3a4a5, you can split it into three child numbers:
Sub1 = a1a2a3
Sub2 = a2a3a4
Sub3 = a3a4a5
For example, a five-digit 20207 can be split
Sub1= 202
Sub2 = 020 (= 20)
Sub3 = 207
Given a positive integer K, you must program to find all the five digits that meet the following conditions between 10000 and 30000,
The condition is that the three sub-numbers sub1, sub2, and sub3 of these five-digit numbers can be divisible by K.
Input
Input is input by the keyboard. Only one line is entered, which is a positive integer K (0 <K <1000 ).
Output
Output to the file. Each line of the output file is a five-digit meeting the conditions, which must be output from small to large.
Repeated output or omission is not allowed. If No solution is available, "No" is output ".

Example
Num. in
15
Num. out
22555
25555
28555
30000

========================================================== ============================= */

# Include <stdio. h>
# Include <string. h>

/* Extract n characters from the left of the string */
Char * left (char * dst, char * src, int n)
{
Char * p = src;
Char * q = dst;
Int len = strlen (src );
If (n> len) n = len;
/* P + = (len-n); * // * starts from the nth character on the right */
While (n --) * (q ++) = * (p ++ );
* (Q ++) = '\ 0';/* is it necessary? It is necessary */
Return dst;
}

/* Extract n characters from the middle of the string */
Char * mid (char * dst, char * src, int n, int m)/* n is the length, and m is the position */
{
Char * p = src;
Char * q = dst;
Int len = strlen (src );
If (n> len) n = len-m;/* from the MTH to the last */
If (m <0) m = 0;/* starts from the first */
If (m> len) return NULL;
P + = m;
While (n --) * (q ++) = * (p ++ );
* (Q ++) = '\ 0';/* is it necessary? It is necessary */
Return dst;
}

/* Extract n characters from the right of the string */
Char * right (char * dst, char * src, int n)
{
Char * p = src;
Char * q = dst;
Int len = strlen (src );
If (n> len) n = len;
P + = (len-n);/* starts from the nth character on the right */
While (* (q ++) = * (p ++ ));
Return dst;
}

Void main ()
{
FILE * p;
Int I, k, outi, count = 0;
Int sub1, sub2, sub3;
Char * strsub1, * strsub2, * strsub3, * strtempnum, * a, * B, * c;

If (p = fopen ("num. out", "AB +") = NULL)
{
Printf ("open file fail! ");
Getch ();
Exit ();
}
Printf ("Please input int number (0 <K <1000 ):");
Scanf ("% d", & k );

For (outi = 10000; outi <= 30000; outi ++)
{
Itoa (outi, strtempnum, 10 );

Left (strsub1, strtempnum, 3 );
Mid (strsub2, strtempnum, 3, 1 );
Right (strsub3, strtempnum, 3 );

/*
A = strsub1;
B = strsub2;
C = strsub3;
Printf ("strsub1 = % s, strsub2 = % s, strsub3 = % s \ n", a, B, c );
*/

Sub1 = atoi (strsub1 );
Sub2 = atoi (strsub2 );
Sub3 = atoi (strsub3 );

/*
Printf ("sub1 = % d, sub2 = % d, sub3 = % d \ n", sub1, sub2, sub3 );
Printf ("sub1k = % d, sub2k = % d, sub3k = % d \ n", sub1 % k, sub2 % k, sub3 % k );
Getch ();
*/
If (sub1% k) = 0 & (sub2% k) = 0 & (sub3% k) = 0)
{
Fprintf (p, "% d \ n", outi );
Count ++;
Printf ("outi = % d \ n", outi );
}
Else
{
Fprintf (p, "% s \ n", "NO ");
}
}
Printf ("Count = % d OK", count );
Fclose (p );
Getch ();
}

Http://www.cnblogs.com/rosesmall/archive/2012/03/27/2420335.html


What is the role of this string processing function in C language?

Strcat (string 1, string 2)
Char s1 [10] = {"abc "}
Char s2 [3] = {"def "}
Printf ("% s", strcat (s1, s2 ))

The output is abcdef.

C string processing functions

Strcpy (p + strlen (q), r); offset strlen (q) from the first address of the array, that is, copy from the position where Element d is located.
After copying, the length of array p is 3 + 5 = 8 (Element d is overwritten)
Strcat (p, q); connects from the end of array p. The length of array p is 8 + 3 = 11.
Array p is defined as char p [20], that is, 20 char storage units are continuously opened in the request, and each char occupies one byte, so sizeof (p) is equal to 20
Is there any problem?

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.