Categories:
.NET (357)
C (330)
C++ (183)
CSS (84)
DBA (2)
General (7)
HTML (4)
Java (574)
JavaScript (106)
JSP (66)
Oracle (114)
Perl (46)
Perl (1)
PHP (1)
PL/SQL (1)
RSS (51)
Software QA (13)
SQL Server (1)
Windows (1)
XHTML (173)
Other Resources:
Does C have anything like the `substr (extract substring) routine present in other languages?
Does C have anything like the `substr (extract substring) routine present in other languages?
✍: Guest
Not as such.
To extract a substring of length LEN starting at index POS in a source string, use something like
char dest[LEN+1];
strncpy(dest, &source[POS], LEN);
dest[LEN] = '\0'; /* ensure \0 termination */
char dest[LEN+1] = "";
strncat(dest, &source[POS], LEN);
or, making use of pointer instead of array notation,
strncat(dest, source + POS, LEN);
(The expression source + POS is, by definition, identical to &source[POS]
Why does strncpy not always place a \0 terminator in the destination string?
strncpy was first designed to handle a now-obsolete data structure, the fixed-length, not-necessarily-\0-terminated ``string.'' strncpy is admittedly a bit cumbersome to use in other contexts, since you must often append a '\0' to the destination string by hand.
You can get around the problem by using strncat instead of strncpy. If the destination string starts out empty (that is, if you do *dest = '\0' first), strncat does what you probably wanted strncpy to do:
*dest = '\0';
strncat(dest, source, n);
This code copies up to n characters, and always appends a \0.
Another possibility is
sprintf(dest, "%.*s", n, source)
(though, strictly speaking, this is only guaranteed to work for n <= 509).
When arbitrary bytes (as opposed to strings) are being copied, memcpy is usually a more appropriate function to use than strncpy.
2015-08-19, 1083👍, 0💬
Popular Posts:
What’ is the sequence in which ASP.NET events are processed ? Following is the sequence in which the...
What Happens If a Hyper Link Points to a Music File? - XHTML 1.0 Tutorials - Understanding Hyper Lin...
How To Set Background to Transparent or Non-transparent? - CSS Tutorials - HTML Formatting Model: Bl...
What is hashing? To hash means to grind up, and that's essentially what hashing is all about. The he...
How To Manage Transaction Isolation Level? - Oracle DBA FAQ - Introduction to PL/SQL Transaction iso...