Strrchr + strcat + strcpy

Source: Internet
Author: User

Http://baike.baidu.com/view/1756792.htm#2

Function Introduction

Function Name: strrchr

Function prototype: char * strrchr (char * STR, char C );

Database: String. h

Function:Returns the position of the last occurrence of a character C in another string Str.(That is, to find the first occurrence position of character C from the right side of Str), and return all characters from this position in the string until the end of the string. If the specified character cannot be found, the function returns NULL.

Related functions: strchr

Example

# Include <string. h>

# Include <stdio. h>

Int main (void)

{

Char string [20];

Char * PTR, c = 'R ';

Strcpy (string, "There are two rings ");

PTR = strrchr (string, C );

If (PTR)

Printf ("the character % C is at position: % s \ n", C, PTR );

Else

Printf ("the character was not found \ n ");

Return 0;

}

The pointer returned by strrchr should point to 'R' in "Rings", rather than 'R' in "there" or "are '.

The running result is: the character R is at position: Rings

Http://baike.baidu.com/view/1028534.htm#1 PrototypeExtern char * strcat (char * DEST, char * SRC );

Usage

# Include <string. h>

In C ++, it is stored in the <cstring> header file.

Function

Returns the SRC string.Add to the end of DeST (equivalent to connection)(Overwrite '\ 0' at the end of DEST) and add' \ 0 '.

Description

The memory areas specified by Src and DEST cannot overlap and DEST must have enough space to hold SRC strings.

Returns the pointer to DeST.

Example

// Strcat. c

# Include <syslib. h>

# Include <string. h>

Main ()

{

Char d [20] = "golden global ";

Char * s = "View ";

Clrscr ();

Strcat (D, S );

Printf ("% s", d );

Getchar ();

Return 0;

}

The program execution result is:

Golden Global View

The strcat function is prototype as follows:

Char * strcat (char * strdest, const char * strsrc) // Add the source string to const, indicating that it is an input parameter

{

Char * address = strdest; // if this statement is placed after assert, a compilation error occurs.

Assert (strdest! = NULL) & (strsrc! = NULL); // Add non-0 assertions to the source and target addresses

While (* strdest) // is while (* strdest! = '\ 0') Simplified Form

{// If while (* strdest ++) is used, an error occurs. Because strdest executes ++ once after the loop ends, strdest

Strdest ++; // points to the next position of '\ 0. /So it must be in the body of the loop ++; because if * strdest refers

} // End sign '\ 0' to the string '.

While (* strdest + = * strsrc ++)

{

NULL; // you can use ++ in this loop condition,

} // The statement * strdest = '\ 0' can be added here; no need

Return address; // return the destination address for chained operations

} Http://baike.baidu.com/view/1026861.htm

C Standard library functions

Prototype Declaration: extern char * strcpy (char * DEST, const char * SRC );

Header file: String. h

Function:Assign a value to the address space starting with the SRC address and containing the null terminator to the address space starting with the Dest (equivalent to overwriting)

Note: The memory areas specified by Src and DEST cannot overlap and DEST must have sufficient space to accommodate SRC strings.

Returns the pointer to DeST.

Edit typical implementation of this section

/**********************

* A typical industrial implementation of the C standard library function strcpy

* Return value:

* Return the address of the target string.

* The ANSI-C99 standard is undefined in case of an exception, so the real determines the return value, usually null.

* Parameters:

* Strdestination

* Target string

* Strsource

* Source string

***********************/

Char * strcpy (char * strdestination, const char * strsource)

{

Assert (strdestination! = NULL & strsource! = NULL );

Char * strd = strdestination;

While (* strdestination ++ = * strsource ++ )! = '\ 0 ')

Return strd;

}

Edit the topic strcpy, which has the highest frequency in this section:

It is known that the prototype of the strcpy function is:

Char * strcpy (char * strdest, const char * strsrc );

1. Implement the strcpy function without calling the library function.

2. Explain why char * is returned *.

Explanation:

1. Implementation Code of strcpy

Char * strcpy (char * strdest, const char * strsrc)

{

Char * strdestcopy = strdest; // [3]

If (strdest = NULL) | (strsrc = NULL) // [1]

Throw "invalid argument (s)"; // [2]

While (* strdest ++ = * strsrc ++ )! = '\ 0'); // [4]

Return strdestcopy;

}

Incorrect practice:

[1]

(A) if the pointer is not checked, it means that the respondent does not pay attention to the robustness of the Code.

(B) used to check the pointer validity ((! Strdest) | (! Strsrc) or (! (Strdest & strsrc). It indicates that the respondent has no deep understanding of implicit conversions of types in C language. In this example, char * is converted to bool, that is, implicit type conversion. Although this function is flexible, it is more likely to increase the error probability and increase the maintenance cost. Therefore, C ++ adds the bool, true, and false keywords to provide a safer conditional expression.

(C) Use (strdest = 0) | (strsrc = 0) to check the pointer validity. This means that the respondent does not know the benefit of using constants. Directly Using a literal constant (such as 0 in this example) reduces the maintainability of the program. 0 is simple, but there may be a lot of pointer checks in the program. In case of PEN mistakes, the compiler cannot find that the generated program contains logical errors and it is difficult to eliminate them. If null is used to replace 0, the compiler will check if a spelling error occurs.

[2]

(A) return new string ("invalid argument (s)"); it indicates that the respondent does not know the purpose of the returned value, and is not cautious about memory leakage. Returning the memory allocated in the function body from the function is very dangerous. It throws the obligation to release the memory to an uninformed caller. In most cases, the caller will not release the memory, which leads to memory leakage.

(B) Return 0;, indicating that the respondent did not master the exception mechanism. The caller may forget to check the return value, and the caller may not be able to check the return value (see the chain expression below ). If you want the return value to shoulder the dual function of returning the correct value and abnormal value, the result is often invalid in both functions. The return value should be replaced by throwing an exception, which can reduce the burden on the caller, prevent errors from being ignored, and enhance the maintainability of the program.

[3]

(A) if you forget to save the original strdest value, it means that the answer provider's logic is not strict.

[4]

(A) cyclically write it as while (* strdest ++ = * strsrc ++);, same as [1] (B ).

(B) cyclically write while (* strsrc! = '\ 0') * strdest ++ = * strsrc ++;, indicating that the respondent does not check the boundary condition effectively. After the loop body ends, '\ 0' is not correctly added to the end of the strdest string '.

2. Return the original strdest value to enable the function to support chained expressions, increasing the "added value" of the function ". Functions of the same function are naturally more ideal if they can reasonably improve availability.

The form of a chained expression is as follows:

Int ilength = strlen (strcpy (stra, strb ));

Another example:

Char * stra = strcpy (New char [10], strb );

The original strsrc value is returned incorrectly. First, the source string must be known and it does not make sense to return it. Second, the expression in the second example cannot be supported. Third, to protect the source string, the const uses const to limit the content referred to by strsrc and returns const char * as char *. If the type is different, an error is returned during compilation.

In the preceding statement, the loop statement while (* strdest ++ = * strsrc ++ )! = '\ 0'); it is difficult to understand. You can understand this sentence as follows.

First:

While (1)

{

Char temp;

Temp = * strdest = * strsrc;

Strdest ++;

Strsrc ++;

If ('\ 0' = temp)

Break;

}

Second:

While (* strsrc! = '\ 0 ')

{

* Strdest = * strsrc;

Strdest ++;

Strsrc ++;

}

* Strdest = * strsrc;

Personal opinion: the throw usage is obviously disconnected. If you want to determine whether to add # include <assert. h>

If the expression value is false, the entire program exits and an error message is output. If the expression value is true, continue executing the following statement.

Before using this macro, the header file assert. h must be included.

# Include <assert. h>

# Include <iostream. h>

Char * strcpy (char * strdest, const char * strsrc)

{

Assert (strdest! = NULL) & (strsrc! = NULL ));

Char * strdestcopy = strdest;

While (* strdest ++ = * strsrc ++ )! = '\ 0 ');

Return strdestcopy;

}

Void main ()

{

Char A [20], C [] = "I am teacher! ";

Strcpy (a, c );

Cout <A <Endl;

}



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.