C Language String Operations Summary encyclopedia

Source: Internet
Author: User
Tags byte sizes character set comparison first string function prototype strcmp strlen versions

1) String manipulation

strcpy (P, p1) copy string
strncpy (P, p1, N) copy the specified length string
Strcat (P, p1) Append string
Strncat (P, p1, N) append specified length string
Strlen (p) Take string length
strcmp (P, p1) comparison string
STRCASECMP ignores case comparison strings
STRNCMP (P, p1, N) compare specified length strings
STRCHR (P, c) finds the specified character in the string
STRRCHR (P, c) reverse lookup in string
Strstr (P, p1) Find string
STRPBRK (P, p1) takes all the characters of the target string as a collection and finds any element of the collection in the current string
STRSPN (P, p1) takes all the characters of the target string as a collection and finds the offset of any element that is not part of the collection in the current string.
STRCSPN (P, p1) takes all the characters of the target string as a collection and finds the offset of any element that belongs to the collection in the current string
* A string handler with the specified length fills the 0 end after the processed string

2 Conversion of string to numeric type
Strtod (P, ppend) converts the double type value from the string p and stores subsequent string pointers to the char* type store that the ppend points to.
Strtol (P, ppend, base) converts a long integer value from the string p, base explicitly sets the integral type of the conversion, set to 0 to determine the system used in accordance with a particular format, 0x, 0X prefix to be interpreted as hexadecimal-format integer, 0 prefix to be interpreted as octal format integer Type
Atoi (p) string conversion to int integral type
Atof (P) string to decimal double
Atol (p) string conversion to Long integer

3) Character check
Isalpha () Check for alphabetic characters
Isupper () Check for uppercase characters
Islower () Check for lowercase alphabetic characters
IsDigit () Check for numbers
Isxdigit () Check if a valid character is represented by a hexadecimal digit
Isspace () Check for space-type characters
Iscntrl () Check for control characters
ISPUNCT () Check for punctuation
Isalnum () Check for letters and numbers
Isprint () Check to see if it is a printable character
Isgraph () Check whether it is a graphical character, equivalent to Isalnum () | Ispunct ()

4) Function prototype
Prototype: strcpy (char destination[], const char source[]);
Function: Copy the string source to the string destination
Routines:
#include <iostream.h>
#include <string.h>
void Main (void)
{
Char str1[10] = {"Tsinghuaok"};
Char str2[10] = {"Computer"};
cout <<strcpy (STR1,STR2) <<endl;
}

The result of the operation is: Computer
The second string will overwrite all the contents of the first string!
Note: When defining an array, the string length of character array 1 must be greater than or equal to the string length of String 2. You cannot assign a string constant or an array of characters directly to an array of characters with an assignment statement. All string-handling functions are included in the header file string.h.


strncpy (char destination[], const char source[], int numchars);

strncpy: Copies the first numchars characters from the string source to the string destination.
Examples of strncpy function applications
Prototypes: strncpy (char destination[], const char source[], int numchars);
Function: Copies the first numchars characters in string source into the string destination
Routines:

#include <iostream.h>
#include <string.h>
void Main (void)
{
Char str1[10] = {"Tsinghua"};
Char str2[10] = {"Computer"};
cout <<strncpy (str1,str2,3) <<endl;
}

Run Result: Comnghua
Note: The first numchars characters in string source will overwrite the NumChars characters in the string destination!

Prototype: strcat (char target[], const char source[]);
Function: source string to the back of the string target
Routines:
#include <iostream.h>
#include <string.h>
void Main (void)
{
Char str1[] = {"Tsinghua"};
Char str2[] = {"Computer"};
cout <<strcpy (STR1,STR2) <<endl;
}

Run Result: Tsinghua Computer

Note: You should consider the length of the character array 2 when defining the length of the character array 1, because the length of the new string is the sum of two string lengths after the connection. After the string is concatenated, the end of the string 1 is automatically removed and a trailing end of the new string is kept at the end of the end string.

Prototypes: Strncat (char target[], const char source[], int numchars);
Function: NumChars characters from string source to the back of the string target
Routines:

#include <iostream.h>
#include <string.h>
void Main (void)
{
Char str1[] = {"Tsinghua"};
Char str2[] = {"Computer"};
cout <<strncat (str1,str2,3) <<endl;
}

Run Result: Tsinghua Com


Prototype: int strcmp (const char firststring[], const char secondstring);
Function: Compare two strings firststring and secondstring
Routines:

#include <iostream.h>
#include <string.h>
void Main (void)
{
Char buf1[] = "AAA";
Char buf2[] = "BBB";
Char buf3[] = "CCC";
int ptr;
ptr = strcmp (BUF2,BUF1);
if (ptr > 0)
cout << "Buffer 2 is greater than buffer 1" <<endl;
Else
cout << "Buffer 2 is less than buffer 1" <<endl;
ptr = strcmp (BUF2,BUF3);
if (ptr > 0)
cout << "Buffer 2 is greater than buffer 3" <<endl;
Else
cout << "Buffer 2 is less than buffer 3" <<endl;
}

Run Result: Buffer 2 is less than buffer 1
Buffer 2 is greater than buffer 3


Prototype: strlen (const char string[]);
Function: Count the number of characters in string strings
Routines:

#include <iostream.h>
#include <string.h>
void Main (void)
{
Char str[100];
cout << "Please enter a string:";
CIN >>str;
cout << "The length of the" string is: "<<strlen (str) <<" a "<<endl;
}

Run result the length of the string is x (the total number of characters you enter)

Note: The function of the strlen function is to compute the actual length of the string, excluding '. In addition, the strlen function can also directly test the length of a string constant, such as: strlen ("Welcome").


void *memset (void *dest, int c, size_t count);
Place the count of Dest before the character C. Returns the value of the dest.

void *memmove (void *dest, const void *SRC, size_t count);
Copy the Count byte character from Src to the dest.  If there is overlap between src and dest, the function is processed automatically. Returns the value of the dest.

void *memcpy (void *dest, const void *SRC, size_t count);
Copy the Count byte character from Src to the dest.  As with memmove functionality, only the SRC and dest overlap are not handled. Returns the value of the dest.

void *memchr (const void *buf, int c, size_t count);
Finds the first occurrence of character C in buf count bytes. The character C is found or the count byte has been searched, and the lookup stops. If the operation succeeds, it returns the position pointer for the first occurrence of C in buf, or null.

void *_memccpy (void *dest, const void *SRC, int c, size_t count);
Copy 0 or more bytes of characters from Src to dest. The copy stops when the character C is copied or the count characters are copied.

If the character c is copied, the function returns a pointer to the character position immediately after the character. Otherwise null is returned.

int memcmp (const void *BUF1, const void *BUF2, size_t count);
Compares the BUF1 and buf2 count byte sizes before.
The return value < 0 indicates that the BUF1 is less than buf2;
The return value is 0, which means that buf1 equals buf2;
The return value > 0 indicates that BUF1 is greater than buf2.

int memicmp (const void *BUF1, const void *BUF2, size_t count);

Compare Buf1 and Buf2 before count bytes. Unlike memcmp, it is not case-sensitive.

The return value is ibid.

Char *strrev (char *string);
Reverses the order of characters in string strings.  The null terminator position is unchanged. Returns a pointer to the adjusted string.

Char *_strupr (char *string);
Replaces all lowercase letters in a string with the corresponding uppercase letters, and the other characters remain unchanged. Returns a pointer to the adjusted string.

Char *_strlwr (char *string);
Replaces all uppercase letters in a string with the corresponding lowercase letters, and the other characters remain unchanged. Returns a pointer to the adjusted string.

Char *strchr (const char *string, int c);
Finds the first occurrence of a string, and the null terminator is also included in the lookup. Returns a pointer to the position in which character C appears for the first time in string strings, or null if it is not found.

Char *strrchr (const char *string, int c);
Looks up the last occurrence of character C in string strings, which is to reverse-order a string, including a null terminator.
Returns a pointer to the position in which the character C was last seen in string strings, or null if it was not found.

Char *strstr (const char *string, const char *strsearch);
Looks up a strsearch substring in string strings. Returns a pointer to the first occurrence of a substring strsearch in a string. If no substring strsearch is found, NULL is returned. If the substring strsearch is an empty string, the function returns a string value.

Char *strdup (const char *strsource);
The function will call the malloc function on its own to allocate storage space for the copy strsource string, and then copy the strsource into the allocated space. Be careful to release this allocated space in time.
Returns a pointer to the space allocated for the copy string; If the allocation space fails, a null value is returned.

Char *strcat (char *strdestination, const char *strsource);
Adds the source string strsource to the target string strdestination, followed by a null terminator after the resulting new string. The strsource character of the source string overrides Terminator null after the target string strdestination. There are no overflow checks in the process of copying or adding strings, so make sure the target string space is large enough.  Cannot handle the case where the source string overlaps with the target string. function returns the Strdestination value.

Char *strncat (char *strdestination, const char *strsource, size_t count);
Adds the count characters starting from the source string strsource to the target string strdest. The strsource character of the source string overrides Terminator null after the target string strdestination. If count is greater than the length of the source string, the count value is replaced with the length value of the source string. The resulting new string is automatically appended with a null terminator. As with the STRCAT function, this function cannot handle the case where the source string overlaps with the target string. function returns the Strdestination value.

Char *strcpy (char *strdestination, const char *strsource);
Copies the source string strsource to the location specified by the destination string strdestination, containing the null terminator. Cannot handle the case where the source string overlaps with the target string. function returns the Strdestination value.

Char *strncpy (char *strdestination, const char *strsource, size_t count);
Copies the count characters starting from the source string strsource to the location specified by the target string strdestination. If the count value is less than or equal to the length of the strsource string, and the null terminator target string is not automatically added, and count is greater than the length of the strsource string, the strsource is filled with the null terminator to fill the count characters and copied to the target string. Cannot handle the case where the source string overlaps with the target string. function returns the Strdestination value.

Char *strset (char *string, int c);
Sets all characters of the string string to character C and encounters a null terminator stop. function returns the adjusted string pointer of the content.

Char *strnset (char *string, int c, size_t count);
Sets the number of string string start to character C, and if the count value is greater than the length of the string, replaces the count value with the length of string. function returns the adjusted string pointer of the content.

size_t strspn (const char *string, const char *strcharset);
Finds the ordinal number of the first occurrence of a character in a string string that is not contained in a strcharset string (except null string terminator). Returns an integer value that specifies the length of a substring of all the characters in characters in string. If string starts with a character that is not contained in strCharSet, the function returns a value of 0.

size_t strcspn (const char *string, const char *strcharset);
Finds the ordinal position of the first occurrence of any character in the strCharSet string in the string string, including null for the string terminator.
Returns an integer value that specifies the length of a substring of all characters in a string that are not characters. If string starts with a character contained in strCharSet, the function returns a value of 0.

Char *strspnp (const char *string, const char *strcharset);
Finds the position pointer for the first occurrence of any character that is not contained in the strCharSet string (except null for the string terminator) in the string string. Returns a pointer to the position in the strCharSet that the character appears for the first time in a string.

Char *strpbrk (const char *string, const char *strcharset);
Finds the first occurrence of any character in the strCharSet string in a string string, and does not contain a string terminator null.
Returns a pointer to the position in the strCharSet where any character appears for the first time in a string. If two string arguments do not contain the same character, a null value is returned.

int strcmp (const char *string1, const char *string2);
Compares string string1 and string2 sizes.
The return value < 0 indicates that the string1 is less than string2;
The return value is 0, which means that string1 equals string2;
The return value > 0 indicates that string1 is greater than string2.

int stricmp (const char *string1, const char *string2);
Compares string string1 and string2 sizes, unlike strcmp, compared to their lowercase versions. The return value is the same as the strcmp.

int Strcmpi (const char *string1, const char *string2);
Equivalent to the STRICMP function, just provides a backward-compatible version.

int strncmp (const char *string1, const char *string2, size_t count);
Compares string string1 and string2 sizes, comparing only the preceding count characters. In the comparison process, the length of any string is less than count, and count is replaced by the length of the shorter string. At this point, if the characters in front of both strings are equal, the shorter string is smaller.
The return value < 0 indicates that the substring of the string1 is less than the substring of the string2;
The return value is 0, which means that the substring of the string1 equals the substring of the string2;
The return value > 0 indicates that the substring of the string1 is greater than the string2 substring.

int strnicmp (const char *string1, const char *string2, size_t count);
Compares string string1 and string2 sizes, comparing only the preceding count characters.  Unlike strncmp, they are compared to their lowercase versions of letters. The return value is the same as strncmp.

Char *strtok (char *strtoken, const char *strdelimit);
Looking for the next tag in the Strtoken string, the Strdelimit character set specifies the delimiters that may be encountered in the current lookup call. Returns a pointer to the next tag found in the Strtoken. If the tag is not found, a null value is returned. Each call modifies the strtoken content, replacing each delimiter encountered with a null character.

C + + concept string manipulation

One, char_traits character characteristic class
1 meaning: Wrapping a generic behavior interface for a particular string of elements so that the container implements specific behavior based on feature information
2 defines a generic type name

typedef _elem CHAR_TYPE;
typedef int INT_TYPE;
typedef streampos POS_TYPE;
typedef streamoff OFF_TYPE;
typedef mbstate_t STATE_TYPE;

Where Int_type represents an integer representation of a character element converting to a specific encoding, Pos_type, Off_type, respectively, as a string index and a string element offset, similar to a pointer in a container iteration, an iteration type and a pointer, and an iterator's offset type. The final state_type is used for the storage stream state, such as error, format control, and so on.

3 defines the character/string manipulation of the wrapper interface so that the general algorithm calls

Assign (A, b) defines the process of assignments the value of B to a character to achieve a.operator = behavior
EQ (A, B) defines the equivalence between a character and a B character, and realizes the behavior of a.operator = =
Lt (A, B) defines the relationship of a less than B and realizes the behavior of A.operator <
Compare (A_ptr, b_ptr, CNT) defines a comparison of two sets of strings, returns an int type, and implements similar memcmp behavior
Length (PTR) defines string lengths to achieve similar strlen behavior
Copy (A_ptr, B_PTR, CNT) defines the replication of two sets of strings to achieve similar memcpy behavior
Move (A_ptr, b_ptr, cnt) defines non-overlapping replication of two sets of strings to achieve similar memmove behavior
Assign (PTR, CNT, CH) defines the process of filling strings to achieve similar memset behavior
To_int_type (CH) defines the conversion process for Char_type to Int_type integral type
To_char_type (n) defines the conversion process for Int_type to Char_type character types
Eq_int_type (A, B) defines the equivalent relationship of two int_type corresponding to the current Char_type type
EOF () Defines the end of the string, using an integer representation
Not_eof (n) defines the end character of a string, and returns 1 if the end character is entered, and the other input returns the original value, that is, never returns EOF ()

4) The Int_type type should be the integer encoding of the current character type

Second, std::string is not a sequence container, there is no front () and back () interface for removing elements from the front and end, using Std::string::operator [] and passing streampos types to obtain specific elements, such as std::string :: Size ()-1 to get the last character as an index


Iii. Initialization of basic_string support
1) Default initialization
2) Distributor
3) Copy Construction
4) Local replication [_roff, _roff + _count)
5) Local replication + splitter
6 C string [_ptr, <null>]
7 C string + _count [_ptr, _ptr + _count)
8 C string + splitter
9 C string + _count + splitter [_ptr, _ptr + _count)

_count * _ch
One) _count * _ch + splitter
12) iterator [_ITF, _ITL)
13) Iterator + splitter

Characters to strings cannot be initialized, but support operator = assignment and operator + = cumulative assignment operations.

Iv. interval Validity of strings
The index access to the string is greater than the valid interval of the string, because the string's implementation of the built-in character buffer for subscript access, so it does not cause an exception, but will get unpredictable results, is usually not available.
When you enter another string as a right value, the count is computed by string size when the number of counts is greater than the string size.
The actual type of Std::basic_string::size_type is size_t, implemented in Visual C + + 7.1 as Unsigned,std::basic_string::npos is statically set to

(Basic_string<_elem, _traits, _alloc>::size_type) (-1);

When an operation such as a substring is found, the function returns the value of NPOs to represent an illegal index.


V. Comparison of strings
Allowed comparison objects
1) Compare (S2) Other strings of the same type
2) Compare (p) C-style string
3) Compare (off, CNT, S2) [out, off + cnt] compared with S2
4) Compare (off, CNT, S2, OFF2, Cnt2) [out, off + cnt] compared with S2 [OFF2, Cnt2]
5) Compare (off, CNT, p) [out, off + CNT] compared with [P, <null>]
6) Compare (off, CNT, p, Cnt2) [out, off + CNT] compared with [P, p + Cnt2]

Returns-1, 0, 1 as comparison results of less than, equal to, and greater than.

  VI, additional data  
1 uses operator + + to accept other strings, C-style strings and character  , and
2) to use Push_back () to append characters to the tail and to make the Back_ by string construction Iterator can access  
3) Append () additional  
        1, append (s) Append string  
        2, append (S, off, CNT) append string s [off, off + cnt)  
  &nbs p;     3, append (p) Append string [P, <null>)  
        4, append (P, CNT) append string [P, p + cnt]  
        5, append (n, c) fill n * c 
        6, append (INF, InL) append input stream [inf, InL)  

4 Insert () inserts
1, insert (off, s2) insertion string
2, inserts (off, S2, OFF2, Cnt2) Insert string s [off2, OFF2 + Cnt2]
3, insert (off, p) insertion string [P, <null>]
4, insert (off, p, CNT) insertion string [P, p + CNT]

5, inserts (OFF, n, c) insert n * C
6. Insert (ITER) element default value fill
7. Insert (ITER, C) inserts a specific element
8, insert (ITER, n, c) inserted n*c
9, insert (ITER, INF, InL) inserted [INF, InL)

5) operator + (A, B)
operator + form supported in string association operator overloading
1, S + S
2, S + P
3, S + C
4, p + S
5, C + S

Vii. find, replace, and clear
1) Find ()
1, found (c, off) in S [Off, NPOs) to find C
2, find (p, off, N) in S [Off, NPOs) search [P, p + N]
3, find (p, off) in S [Off, NPOs) search [P, <null>]
4, find (S2, off) in S [Off, NPOs) search s2

2) A variant of Find ()  
        1, RFind () has the input form of finding (), and the reverse sequence lookup  
 & nbsp;      2, Find_first_of () has the input form of find (), returns the first matching index  
         3, Find_last_of () has the input form of find (), returns the penultimate matching index  
         4, find_first_not_of () has the input form of find (), returns the first mismatched index  
        5, find The _last_not_of () has the input form of find (), returning the first inverse mismatched index  

3 replace () replacement
1. Replace (off, CNT, S2) replaces s [off, off + cnt] into S2
2. Replace (off, CNT, S2, OFF2, Cnt2) replaces S [off, off + cnt) to S2 [off2, OFF2 + Cnt2]
3. Replace (off, CNT, p) replaces S [off, off + cnt] (p, <null>)
4. Replace (off, CNT, p, Cnt2) replaces S [Off, off, and CNT] with [P, p + Cnt2]

5. Replace (off, CNT, N, c) replaces S [off, off + cnt) with C * N

Using iterators:
6. Replace (INF, InL, S2) replaces [INF, InL) with S2
7. Replace (INF, InL, p) replaces [INF, InL) with [P, <null>)
8. Replace (INF, InL, p, CNT) replaces [INF, InL) with [P, p + CNT]
9. Replace (INF, InL, N, c) replaces [INF, InL) with n * C
10. Replace (INF, InL, INF2, InL2) replaces [INF, InL) with [InF2, InL2]

4) Erase () Delete
1, erase (off, CNT) from the string s to remove S [off, off + CNT)
2, Erase (ITER) removed from the string s *iter
3, Erase (ItF, ITL) Delete from string s [ItF, ITL)

Eight, take out the string
1 Get C-style string
C_STR () returns the C-style string pointer of the constant type, copy (PTR, cnt, off = 0) copies the specified size string to a specific pointer. Data () only invokes the C_STR () implementation in Visual C + + 7.1.
2) Get substring
SUBSTR (off, CNT) obtains a copy of S [off, off + cnt].
3) Copying a substring
Copy (P, off, CNT) copies S [Off, off, and CNT] to p.


Ix. Buffer Management of strings
Strings have a buffer management interface similar to std::vector.
Size () to get a valid element length
Max_size () to obtain the active space allocated by the current memory allocator
Reserve () reserve space for buffer
Capacity () Gets the capacity of the buffer
Resize () resets the length of a string to specify an initialization value for it

Define the end of the input iterator
Passing an input stream object to the Istream_iterator to create an input iterator, the input iterator holds a pointer to the input stream object, and when the default create and read stream fails, the pointer is set to 0. And when implementing the operator = = Equality operation between input iterators, an equality comparison of the held stream object pointers is performed, so that the input iterator created by default will be used to match the end of the input stream.

* When the input stream fails to read, the user executes if, while the condition is judged, the judgment value is actually converted to the void* type, or according to the operator! operator returns the result of the input stream overload operator void* and operator! operator, you can define the behavior of an input stream in a Boolean expression, so that when a stream fails to read, the input iterator can be validated by a Boolean expression rather than an explicit access to the fail () member function.

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.