W3Schools is a popular tutorial website, and its C string functions reference covers the standard C library functions declared in <string.h> and <ctype.h> that operate on null-terminated character arrays. These functions let you copy, concatenate, compare, search, and analyze strings in C. This article explains what those functions do, how to use them correctly, and common pitfalls.
What Are C String Functions?
In C, a string is simply an array of char values ending with a null character ('\0'). The C standard library provides a set of functions to manipulate these arrays without having to write loops manually. W3Schools groups them into categories: string manipulation (strcpy, strcat), string comparison (strcmp), string searching (strchr, strstr), and character classification (isalpha, isdigit).
Core String Functions on W3Schools
W3Schools lists the most commonly used functions. Here are the key ones with examples:
strlen(str)– returns the length ofstr, not counting the null terminator. Example:strlen("hello")returns 5.strcpy(dest, src)– copiessrcintodest(including the null). Ensuredesthas enough space.strcat(dest, src)– appendssrcto the end ofdest. The null ofdestis overwritten.strcmp(str1, str2)– compares two strings lexicographically. Returns 0 if equal, negative ifstr1is less, positive if greater.strchr(str, ch)– finds the first occurrence of characterchinstrand returns a pointer to it, or NULL if not found.strstr(haystack, needle)– finds the first occurrence of substringneedleinhaystack.
How to Use Them Correctly
To use these functions, include <string.h> at the top of your C file. For character functions like isalpha, include <ctype.h>. Here’s a simple example that copies and concatenates:
#include <stdio.h>
#include <string.h>
int main() {
char dest[20] = "Hello";
char src[] = " World";
strcat(dest, src);
printf("%s\n", dest); // prints "Hello World"
return 0;
}
Always ensure the destination array is large enough to hold the result plus the null terminator. For strcpy and strcat, there is no automatic bounds checking.
Common Pitfalls and Safety
Buffer overflows are the biggest risk. If dest is too small, strcpy and strcat will write past the end, causing undefined behavior and potential security vulnerabilities. Safer alternatives exist:
strncpy(dest, src, n)– copies at mostncharacters, but may not null-terminate ifsrcis longer thann.strncat(dest, src, n)– appends at mostncharacters and always null-terminates.snprintf(dest, size, "%s", src)– writes at mostsize-1characters and always null-terminates. This is often the safest way to copy strings.
Another pitfall: strcmp compares byte values, not human-friendly alphabetical order. For case-insensitive comparison, you need to convert characters with tolower or toupper first.
Character Classification Functions
W3Schools also covers functions from <ctype.h> that test single characters:
isalpha(c)– true ifcis a letter.isdigit(c)– true ifcis a digit (0-9).isalnum(c)– true if letter or digit.isspace(c)– true if whitespace (space, tab, newline, etc.).tolower(c)andtoupper(c)– convert case.
These are handy for validating input. For example, to check if a string is all digits, loop through each character and use isdigit.
Comparing Strings: strcmp vs. strncmp
strcmp compares entire strings, while strncmp compares only the first n characters. Use strncmp when you want to check a prefix. Example:
if (strncmp(str, "http://", 7) == 0) {
// str starts with "http://"
}
Remember that strcmp returns 0 for equality, which is counterintuitive for many beginners. Always compare to 0, not to 1.
Searching Within Strings
Besides strchr and strstr, there are related functions:
strrchr(str, ch)– finds the last occurrence of characterch.strpbrk(str, charset)– finds the first occurrence of any character fromcharsetinstr.strspn(str, charset)– returns the length of the initial segment ofstrthat consists only of characters fromcharset.
These are useful for parsing. For instance, strpbrk can find the first delimiter in a line of text.
Alternatives and Modern C
For dynamic strings, many C programmers use libraries like GString from GLib or write their own. C11 introduced strdup (POSIX, not standard) and strndup to duplicate strings, but they are not part of the ISO C standard. In C23, strdup and strndup were added, but support varies. For safety, consider using snprintf for copying and strncat for concatenation.
Frequently Asked Questions
Q: How do I get the length of a string in C?
Use strlen(str). It returns the number of characters before the null terminator. For example, strlen("test") returns 4.
Q: Why does strcmp return 0 when strings are equal?
Because strcmp returns the difference between the first differing characters. If there is no difference, it returns 0. This is a common convention in C: 0 means “no difference” or “equal”. Always check if (strcmp(a,b) == 0) for equality.
Q: How do I concatenate two strings safely?
Use strncat(dest, src, sizeof(dest) - strlen(dest) - 1) to avoid overflow. Even better, use snprintf(dest + strlen(dest), remaining, "%s", src). Always leave room for the null terminator.
Q: What is the difference between strcpy and strncpy?strcpy copies the entire string including the null. strncpy copies at most n characters, but if src is shorter, it pads with nulls; if longer, it does not null-terminate. This can cause bugs, so prefer snprintf.
Q: Can I use these functions on strings declared as char*?
Yes, as long as the pointer points to a valid, null-terminated array. For string literals, be careful: modifying them is undefined behavior, so use char str[] = "hello"; instead of char* str = "hello"; if you plan to change it.
Q: Are there functions to convert a string to an integer?
Yes, atoi(str) converts to int, but it has no error checking. Better use strtol(str, &endptr, 10) which gives you a pointer to the first invalid character. W3Schools includes these under stdlib.h, not string.h.
Related
- Google Sheets Number Filter: How to Use It
- Shortcut to Save a Document: Ctrl+S vs Cmd+S
- Google Dividend Per Share: Current Rate & History
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- COUNTIF with Multiple Ranges: How to Do It in ExcelYou cannot use a single COUNTIF function with multiple separate ranges in Excel—COUNTIF only accepts one range. To…
- INDIRECT in Excel: How to Drag Formulas to New CellsIf you want an INDIRECT formula to follow different cells as you drag it, build its address from…
- COUNTIFS Formula for Date Range in Excel With ExamplesTo count dates within a range in Excel, use COUNTIFS with a start-date criterion and an end-date criterion.…
- Excel Date Difference Formulas for Days, Months, and YearsTo find the number of elapsed days between two dates in Excel, subtract the start date from the…
- Excel Delete Every X Rows: Safe Methods and FormulasYes. In Microsoft Excel for Microsoft 365 on Windows, add a helper column to mark every xth data…
- VLOOKUP HLOOKUP Combination: How to Use BothYes, you can combine VLOOKUP and HLOOKUP in a single formula to look up a value that requires…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.