Implementation Principles of several common string processing functions

Source: Internet
Author: User

StringIt is a common data structure that can process strings flexibly. Therefore, strings are widely used in actual development, especially in non-numeric processing. Although many string operations are encapsulated in the function library, the application can directly call the library function to implement string processing. However, if developers can understand the underlying implementation principle, it is of great benefit for application programming.

This article mainly introduces the implementation principles of several frequently used string processing functions.

I. strlen Functions

Strlen function: calculates the actual length of a string, excluding '\ 0 '.

Algorithm: starts scanning from the first character until the first '\ 0' is met, stops scanning, and returns the string length.

The Code is as follows:

int strlen(const char *str){        int n=0;        assert(str!=NULL);        while(*str++!='\0')        ++n;        return n;}

 
 

Ii. strcat Functions

Strcat function: adds the source string str2 to the end of the target string str1, overwrites the '\ 0' at the end of str1, and adds' \ 0' to the end of the new str1 ', returns the pointer to str1.

Algorithm: Scan str1 until '\ 0' is met. Add str2 to the end of str1 one by one, and then add' \ 0 '.

The Code is as follows:

char *strcat(char *str1, const char *str2){char *p=str1;assert( (str1!=NULL) && (str2!=NULL) ); while(*str1!='\0')str1++;while(*str1++=*str2++);return p;}

Iii. strcmp Functions

Strcmp function: returns the size of two strings, namely, str1 and str2. If str1> str2, a positive number is returned. If str1 <str2, a negative number is returned. If str1 = str2, returns 0.

Algorithm: compares each character of str1 and str2 one by one. If the character is equal and the character '\ 0' is not met, the next character of str1 and str2. otherwise, the difference between * str1 and * str2 is returned.

The Code is as follows:

int strcmp(const char *str1, const char *str2){assert( (str1!=NULL) && (str2!=NULL) );while(*str1 && *str2&& (*str1==*str2)) {str1++;str2++;}return *str1 - *str2;}

Iv. strcpy Functions

Strcpy function: Copy str2 (including null) to str1, and return a pointer to str1.

Algorithm: add characters in str2 to the address space pointed to by str1 one by one. Ensure that the address space pointed to by str1 is large enough.

The Code is as follows:

char *strcpy(char *str1, const char *str2) {char *p=str1;assert( (str1!=NULL) && (str2!=NULL) );while(*str1++=*str2++);return p; }

V. atoi Functions

Atoi function: converts a string to an integer.

Algorithm: Skip spaces or tabs, deduce symbols, and then subtract '0' to convert integers. Skip non-numeric values and return the converted integers.

The Code is as follows:

int atoi(char *str){int sum=0,sign=1;char *p=str;assert(str!=NULL);if(' '==*p||'\t'==*p)p++;if('-'==*p)sign=-1;if('-'==*p||'+'==*p)p++;while(*p>='0' && *p<='9'){sum = sum*10 + *p-'0';p++;}return sign*sum;}

Vi. ITOA Functions

ITOA function: converts an integer to a string.

Algorithm: first, deduce the integer symbol. If it is negative, convert it to positive. Store the integer from the single digit to the highest digit in the TMP temporary array. If it is a negative integer, then add a negative number. Put the elements of the temporary array in the STR character array in reverse order, and add an empty character at the end.

The Code is as follows:

void itoa(int num, char str[]){int i=0,j=0,sign=num;char tmp[10];if(num<0)num=-num;do{tmp[i++]=num%10 + '0';num/=10;}while(num>0);if(sign<0)tmp[i++]='-';tmp[i]='\0';i--;while(i>=0){str[j]=tmp[i];j++;i--;}str[j]='\0';}

Also: replace substrings

In most cases, you may encounter the requirement to replace the substring in the string. Several issues need to be considered:

1. Overflow

If the question needs to be replaced with the original string, you must consider whether the length of the string after replacement will be greater than the set length. If you can create a new string, you can set the size by yourself, in this case, there is generally no overflow problem.

2. The length ratio of the substring to be replaced and the length ratio of the substring to be replaced is invalid.

Here we will take the next question as an example:

Question: implement a function to replace every space in the string with "% 20". For example, if "We are happy." Is input, "We % 20are % 20happy." Is output .".

Solution 1: Create a new string to store the replaced string;

The Code is as follows:

# Include <stdio. h> int main () // directly implement the main function {char STR [20] = "we are happy. ", str1 [30] =" \ 0 "; char * P = STR; int I = 0; while (* P! = '\ 0') {If (* P! = '') Str1 [I ++] = * P ++; else {str1 [I ++] = '%'; str1 [I ++] = '2 '; str1 [I ++] = '0'; P ++ ;}} printf ("str1 = % s \ n", str1); Return 0 ;}

Solution 2: replace the original string with spaces from the back to the front;

The Code is as follows:

Void replaceblank (char string [], int length) {If (string = NULL & length <= 0) return; /* originallength is the actual length of string */INT originallength = 0; int numberofblank = 0; int I = 0; while (string [I]! = '\ 0') {++ originallength; If (string [I] = '') ++ numberofblank; ++ I ;} /* newlength is the length after the space is replaced with '% 20' */INT newlength = originallength + numberofblank * 2; If (newlength> length) return; int indexoforiginal = originallength; int indexofnew = newlength; while (indexoforiginal> = 0 & indexofnew> indexoforiginal) {If (string [indexoforiginal] = '') {string [indexofnew --] = '0 '; string [indexofnew --] = '2'; string [indexofnew --] = '%';} else {string [indexofnew --] = string [indexoforiginal];} -- indexoforiginal ;}}
Wednesday, July 09,201 4

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.