C string substr example
The substr() function of std::string is used to extract substrings. 1. pos is the starting index (starting from 0), len is the number of characters (optional, default to the end); 2. If pos is equal to the length of the string, return an empty string; 3. If pos exceeds the length, throw a std::out_of_range exception; 4. If len exceeds the remaining characters, automatically truncates; 5. Use the size_t type to avoid negative indexing. Examples include extracting fixed-length substrings, obtaining file extensions, and splitting path file names. When using them, you need to ensure that pos is effective to prevent exceptions.
In C, the substr()
function of std::string
is used to extract substrings from strings. It is a very common operation, with simple syntax and easy to use.

Basic syntax
string substr(size_t pos = 0, size_t len = npos) const;
-
pos
: Start position (index, starting from 0) -
len
: The number of characters to be extracted (optional, default to the end of the string)
Returns a new string containing a substring starting from pos
and up to len
characters.
Sample code
#include <iostream> #include <string> using namespace std; int main() { string str = "Hello, World!"; // 1. Starting from position 7, extract 5 characters string sub1 = str.substr(7, 5); cout << "sub1: " << sub1 << endl; // Output: World // 2. Starting from position 0, extract the first 5 characters string sub2 = str.substr(0, 5); cout << "sub2: " << sub2 << endl; // Output: Hello // 3. Start at position 7 and extract to the end (omit len) string sub3 = str.substr(7); cout << "sub3: " << sub3 << endl; // Output: World! // 4. Extract the entire string string sub4 = str.substr(); cout << "sub4: " << sub4 << endl; // Output: Hello, World! // 5. Out_of_range exception will be thrown if the start position exceeds the length try { string sub5 = str.substr(20); cout << "sub5: " << sub5 << endl; } catch (const out_of_range& e) { cout << "Error: " << e.what() << endl; } return 0; }
Common usage and precautions
✅ Correct usage
- Index starts at 0
-
len
can exceed the remaining characters,substr
will automatically intercept the end - If
pos == str.length()
, return an empty string - If
pos > str.length()
, throwstd::out_of_range
❌ Common Errors
str.substr(-1, 3); // Error! pos is size_t unsigned type, -1 will become a maximum value
Practical Tips: Get File Extensions
string filename = "example.txt"; size_t dotPos = filename.rfind('.'); if (dotPos != string::npos) { string ext = filename.substr(dotPos 1); cout << "Extension: " << ext << endl; // Output: txt }
Split string (simple example)
string path = "/home/user/file.txt"; size_t lastSlash = path.rfind('/'); if (lastSlash != string::npos) { string filename = path.substr(lastSlash 1); cout << "Filename: " << filename << endl; // Output: file.txt }
Basically that's it. substr()
is simple but easily ignores boundary issues. When using it, please pay attention to check whether the position is valid.

The above is the detailed content of C string substr example. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

When opening the software or game, a prompt suddenly appears that "the application cannot start normally (0xc0000906)" appears, and many users will be confused and don't know where to start. In fact, most of these errors are caused by corruption of system files or missing runtime libraries. Don't rush to reinstall the system. This article provides you with several simple and effective solutions to help you quickly restore the program to run. 1. What is the error of 0xc0000906? Error code 0xc0000906 is a common startup exception in Windows systems, which usually means that the program cannot load the necessary system components or running environment when running. This problem often occurs when running large software or games. The main reasons may include: the necessary runtime library is not installed or damaged. The software installation package is endless

The computer prompts "MsVCP71.dll is missing from the computer", which is usually because the system lacks critical running components, which causes the software to not load normally. This article will deeply analyze the functions of the file and the root cause of the error, and provide three efficient solutions to help you quickly restore the program to run. 1. What is MSVCP71.dll? MSVCP71.dll belongs to the core runtime library file of Microsoft VisualC 2003 and belongs to the dynamic link library (DLL) type. It is mainly used to support programs written in C to call standard functions, STL templates and basic data processing modules. Many applications and classic games developed in the early 2000s rely on this file to run. Once the file is missing or corrupted,

To use regular expressions in C, you need to include header files and use the functions it provides for pattern matching and text processing. 1. Use std::regex_match to match the full string, and return true only when the entire string conforms to the pattern; 2. Use std::regex_search to find matches at any position in the string; 3. Use std::smatch to extract the capture group, obtain the complete match through matches[0], matches[1] and subsequent sub-matches; 4. Use std::regex_replace to replace the matching text, and support the capture group with references such as $1 and $2; 5. You can add an iset when constructing the regex (

Operator overloading in C allows new behaviors of standard operators to be assigned to custom types, 1. Return new objects through member function overloading; 2. Overload = Modify the current object and return reference; 3. Friend function overloading

The basic usage of std::vector includes: 1. Declare vector; 2. Add elements with push_back(); 3. Initialize with initialization list; 4. Loop traversal with range for; 5. Access elements through index or back(); 6. Direct assignment of values to modify elements; 7. Delete the end elements with pop_back(); 8. Call size() to get the number of elements; it is recommended to use constauto& to avoid copying, pre-allocate reserve() to improve performance, and pay attention to checking that it is not empty before access. This data structure is an efficient and preferred way to handle string lists.

std::variant is a type-safe union introduced by C 17. It can safely hold the value of one of the specified types. It can realize secure access and type checking through methods such as std::get, std::holds_alternative, std::visit and std::get_if. Combined with std::monostate, optional values can be simulated. It is recommended to use std::visit for type distribution and avoid large type lists to improve maintainability, and ultimately ensure type safety and exception safety.

In C, the choice of std::map and std::unordered_map depends on the specific requirements. 1. Different underlying structures: std::map is implemented based on red and black trees, with keys stored in order, default ascending order, and the complexity of search and insertion is O(logn); std::unordered_map uses a hash table, unordered, and the average complexity of search and insertion is O(1), and the worst is O(n). 2. Insertion performance and memory overhead: map insertion requires maintenance of tree structure and is less efficient; unordered_map insertion is faster but consumes more memory, and can be optimized through reserve(). 3. Custom comparison function: map supports custom comparison function, unordered

AbasicMakefileautomatesC compilationbydefiningruleswithtargets,dependencies,andcommands.2.KeycomponentsincludevariableslikeCXX,CXXFLAGS,TARGET,SRCS,andOBJStosimplifyconfiguration.3.Apatternrule(%.o:%.cpp)compilessourcefilesintoobjectfilesusing$
