How to extract a substring from a string in the C programming language?
In C language, you can use the following method to extract substrings:
- Using array indexing: you can extract a part of a string by specifying the starting index and ending index. For example, if you have a string str, with starting index as start and ending index as end, you can obtain a substring in the following way:
char newStr[end - start + 1]; // 创建一个新的字符数组来存储子串
int j = 0;
for (int i = start; i <= end; i++) {
newStr[j++] = str[i];
}
newStr[j] = '\0'; // 添加字符串结束符
- copy the string
- copy a portion of a string into another string
- copy a certain number of characters from one string to another
char newStr[end - start + 1]; // 创建一个新的字符数组来存储子串
strncpy(newStr, str + start, end - start);
newStr[end - start] = '\0'; // 添加字符串结束符
Please note that the above examples assume that the input starting and ending indexes are valid and will not access strings beyond their boundaries. In real-life applications, it is important to conduct boundary checks and error handling according to specific requirements.