`
javahigh1
  • 浏览: 1223224 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

Basic String Handling Functions

 
阅读更多

All the string handling functions are prototyped in:

#include <string.h>

The common functions are described below:

char *stpcpy (const char *dest,const char *src) -- Copy one string into another.
int strcmp(const char *string1,const char *string2) - Compare string1 and string2 to determine alphabetic order.
char *strcpy(const char *string1,const char *string2) -- Copy string2 to stringl.
char *strerror(int errnum) -- Get error message corresponding to specified error number.
int strlen(const char *string) -- Determine the length of a string.
char *strncat(const char *string1, char *string2, size_t n) -- Append n characters from string2 to stringl.
int strncmp(const char *string1, char *string2, size_t n) -- Compare first n characters of two strings.
char *strncpy(const char *string1,const char *string2, size_t n) -- Copy first n characters of string2 to stringl .
int strcasecmp(const char *s1, const char *s2) -- case insensitive version of strcmp().
int strncasecmp(const char *s1, const char *s2, int n) -- case insensitive version of strncmp().

The use of most of the functions is straightforward, for example:

char *str1 = "HELLO";
char *str2;
int length;

length = strlen("HELLO"); /* length = 5 */
(void) strcpy(str2,str1);

Note that both strcat() and strcopy() both return a copy of their first argument which is the destination array. Note the order of the arguments is destination array followed by source array which is sometimes easy to get the wrong around when programming.

The strcmp() function lexically compares the two input strings and returns:

Less than zero
-- if string1 is lexically less than string2
Zero
-- if string1 and string2 are lexically equal
Greater than zero
-- if string1 is lexically greater than string2

This can also confuse beginners and experience programmers forget this too.

The strncat(), strncmp,() and strncpy() copy functions are string restricted version of their more general counterparts. They perform a similar task but only up to the first n characters. Note the the NULL terminated requirement may get violated when using these functions, for example:

char *str1 = "HELLO";
char *str2;
int length = 2;


(void) strcpy(str2,str1, length); /* str2 = "HE" */

str2 is NOT NULL TERMINATED!! -- BEWARE

String Searching

The library also provides several string searching functions:

char *strchr(const char *string, int c) -- Find first occurrence of character c in string.
char *strrchr(const char *string, int c) -- Find last occurrence of character c in string.
char *strstr(const char *s1, const char *s2) -- locates the first occurrence of the string s2 in string s1.
char *strpbrk(const char *s1, const char *s2) -- returns a pointer to the first occurrence in string s1 of any character from string s2, or a null pointer if no character from s2 exists in s1
size_t strspn(const char *s1, const char *s2) -- returns the number of characters at the begining of s1 that match s2.
size_t strcspn(const char *s1, const char *s2) -- returns the number of characters at the begining of s1 that do not match s2.
char *strtok(char *s1, const char *s2) -- break the string pointed to by s1 into a sequence of tokens, each of which is delimited by one or more characters from the string pointed to by s2.
char *strtok_r(char *s1, const char *s2, char **lasts) -- has the same functionality as strtok() except that a pointer to a string placeholder lasts must be supplied by the caller.

strchr() and strrchr() are the simplest to use, for example:

char *str1 = "Hello";
char *ans;

ans = strchr(str1,'l');

After this execution, ans points to the location str1 + 2

strpbrk() is a more general function that searches for the first occurrence of any of a group of characters, for example:

char *str1 = "Hello";
char *ans;

ans = strpbrk(str1,'aeiou');

Here, ans points to the location str1 + 1, the location of the first e.

strstr() returns a pointer to the specified search string or a null pointer if the string is not found. If s2 points to a string with zero length (that is, the string ""), the function returns s1. For example,

char *str1 = "Hello";
char *ans;

ans = strstr(str1,'lo');

will yield ans = str + 3.

strtok() is a little more complicated in operation. If the first argument is not NULL then the function finds the position of any of the second argument characters. However, the position is remembered and any subsequent calls to strtok() will start from this position if on these subsequent calls the first argument is NULL. For example, If we wish to break up the string str1 at each space and print each token on a new line we could do:

char *str1 = "Hello Big Boy";
char *t1;


for ( t1 = strtok(str1," ");
      t1 != NULL;
      t1 = strtok(NULL, " ") )

printf("%s/n",t1);

Here we use the for loop in a non-standard counting fashion:

  • The initialisation calls strtok() loads the function with the string str1
  • We terminate when t1 is NULL
  • We keep assigning tokens of str1 to t1 until termination by calling strtok() with a NULL first argument.

    Memory Operations: <memory.h>

    Finally we briefly overview some basic memory operations. Although not strictly string functions the functions are prototyped in #include <string.h>:

    void *memchr (void *s, int c, size_t n) -- Search for a character in a buffer .
    int memcmp (void *s1, void *s2, size_t n) -- Compare two buffers.
    void *memcpy (void *dest, void *src, size_t n) -- Copy one buffer into another .
    void *memmove (void *dest, void *src, size_t n) -- Move a number of bytes from one buffer lo another.
    void *memset (void *s, int c, size_t n) -- Set all bytes of a buffer to a given character.

    Their use is fairly straightforward and not dissimilar to comparable string operations (except the exact length (n) of the operations must be specified as there is no natural termination here).

    Note that in all case to bytes of memory are copied. The sizeof() function comes in handy again here, for example:

    char src[SIZE],dest[SIZE];
    int  isrc[SIZE],idest[SIZE];
    
    memcpy(dest,src, SIZE); /* Copy chars (bytes) ok */
    
    memcpy(idest,isrc, SIZE*sizeof(int)); /* Copy arrays of ints */
    

    memmove() behaves in exactly the same way as memcpy() except that the source and destination locations may overlap.

    memcmp() is similar to strcmp() except here unsigned bytes are compared and returns less than zero if s1 is less than s2 etc.

分享到:
评论

相关推荐

    The C Cheat Sheet - An Introduction to Programming in C

    9.9 String Handling 9.10 Time Functions 9.11 Floating-Point Math 9.12 Standard I/O 10.0 Tips, Tricks, and Caveats 10.1 Infinite Loops 10.2 Unallocated Storage 10.3 The Null Statement 10.4 Extraneous ...

    Program in LUA 2nd Edition.rar

    20.1 Basic String Functions 175 20.2 Pattern-Matching Functions 177 20.3 Patterns 180 20.4 Captures 183 20.5 Replacements 185 20.6 Tricks of the Trade 189 21 The I/O Library 193 21.1 The Simple...

    PHP and MYSQL Bilbe [英文原版]

    Chapter 22: String and Regular Expression Functions 421 Chapter 23: Filesystem and System Functions 439 Chapter 24: Sessions, Cookies, and HTTP 455 Chapter 25: Types and Type Conversions 479 Chapter ...

    The GNU C Library

    * 5 String and Array Utilities * 6 Character Set Handling * 7 Locales and Internationalization * 8 Message Translation * 9 Searching and Sorting * 10 Pattern Matching * 11 Input/Output Overview...

    AT&T Assembly Language

    Building your own string functions 285 Comparing Strings 286 The CMPS instruction 286 Using REP with CMPS 288 String inequality 289 Scanning Strings 291 The SCAS instruction 292 Scanning for multiple ...

    MySql存储过程编程.chm

    String Functions Section 9.2. Numeric Functions Section 9.3. Date and Time Functions Section 9.4. Other Functions Section 9.5. Conclusion Chapter 10. Stored Functions Section 10.1. ...

    C++标准(Standard for Programming Language C++)

    21.4 Class template basic_string 608 21.5 Numeric Conversions 635 21.6 Null-terminated sequence utilities . 636 22 Localization library 640 22.1 General 640 22.2 Header &lt;locale&gt; synopsis 640 22.3 ...

    python3.6.5参考手册 chm

    PEP 498: Formatted string literals PEP 526: Syntax for variable annotations PEP 515: Underscores in Numeric Literals PEP 525: Asynchronous Generators PEP 530: Asynchronous Comprehensions PEP 487:...

    JavaScript权威指南

    Basic Event Handling Section 19.2. Advanced Event Handling with DOM Level 2 Section 19.3. The Internet Explorer Event Model Section 19.4. The Netscape 4 Event Model Chapter 20. ...

    C++ Programming: From Problem Analysis to Program Design, 8th Edition

    Namespaces, The Class String, And User-Defined Simple Data Types. Chapter 8. Arrays. Chapter 9. Records (Structs). Chapter 10. Classes And Data Abstraction. Chapter 11. Inheritance And Composition. ...

    FastReport 3.0 Trial for Delphi5 无源码

    Standard Pascal features: variables, constants, procedures, functions (nested allowed) with var/const/default parameters, all standard operators and statements (includind case, try/finally/except, ...

    FastReport 3.0 Trial for Delphi6 无源码

    Standard Pascal features: variables, constants, procedures, functions (nested allowed) with var/const/default parameters, all standard operators and statements (includind case, try/finally/except, ...

    FastReport 3.0 Trial for Delphi7 无源码

    Standard Pascal features: variables, constants, procedures, functions (nested allowed) with var/const/default parameters, all standard operators and statements (includind case, try/finally/except, ...

    PROGRAMMING ACTIONSCRIPT 3.0

    Basic event handling...34 Examining the event-handling process... 35 Event-handling examples.. 39 Creating object instances...40 Common program elements..42 Example: Animation portfolio piece44 ...

    Professional Assembly Language

    Chapter 10, “Working with Strings,” presents the various assembly language string-handling instruc- tions. Character data is another important facet of high-level language programming. Understanding...

    Packtpub.Python.2.6.Text.Processing.Beginners.Guide.Dec.2010

    You move on to extracting text from a collection of sources and handling it using Python’s built-in string functions and regular expressions. You look into processing structured text documents such ...

    C++.Programming.From.Problem.Analysis.to.Program.Design.7th.Edition

    Namespaces, the class string, and User-Defined Simple Data Types. Chapter 8. Arrays. Chapter 9. Records (structs). Chapter 10. Classes and Data Abstraction. Chapter 11. Inheritance and Composition. ...

    C.Programming.Step.By.Step.Beginners.To.Experts.Edition.B011EXMV7Q

    Are you wanting a shortcut from basic to expert in one day and all the technical jargon removed so its made easy to understand? If you are having doubts learning the language, do not! C is actually ...

    Microsoft Library MSDN4DOS.zip

    MOVS/MOVSB/MOVSW/MOVSD Move Data from String to String MOVSX Move with Sign-Extend MOVZX Move with Zero-Extend MUL Unsigned Multiplication of AL or AX NEG Two's Complement Negation NOP No Operation ...

    一个跨平台的CString源码

    // the Standard C++ Library basic_string&lt;&gt; template and add to it the // the following conveniences: // - The full MFC CString set of functions (including implicit cast) // - writing to/reading ...

Global site tag (gtag.js) - Google Analytics