简体   繁体   English

如何在 C 中创建 char* 字符串的 char* substring?

[英]How to create a char* substring of a char* string in C?

I want to create a substring, which I see online everywhere and it makes sense.我想创建一个 substring,我在网上到处都能看到它,这很有意义。 However, is there any way to, instead of outputting to a regular array of characters, output the substring as a char* array?但是,有什么方法可以将 output 和 substring 作为 char* 数组输出到常规字符数组?

This is the idea of my code:这是我的代码的想法:

char *str = "ABCDEF";
char *subStr = calloc(3, sizeof(char));
memcpy(subStr, &str[3], 3);
fprintf(log, "Substring: %s", subStr);

I am hoping this will print out DEF.我希望这会打印出 DEF。 Let me know what you guys think I should do, or if this will work.让我知道你们认为我应该做什么,或者这是否可行。 Thanks!谢谢!

If you need just to output a substring then you can write如果你只需要 output 和 substring 那么你可以写

fprintf(log, "Substring: %.*s", 3, str + 3);

Here is a demonstrative program.这是一个演示程序。

#include <stdio.h>

int main(void) 
{
    char *str = "ABCDEF";
    FILE *log = stdout;
    
    fprintf(log, "Substring: %.*s", 3, str + 3);
    
    return 0;
}

The program output is程序 output 是

Substring: DEF

Your code does not create C substring as you allocate only 3 element char array, but you also need the 4th one for the null terminating character.您的代码不会创建 C substring 因为您只分配了 3 个元素的字符数组,但您还需要第 4 个用于 null 终止字符。

char *str = "ABCDEF";
char *subStr = calloc(4, sizeof(char));
memcpy(subStr, &str[3], 3);

or less expensive或更便宜

char *str = "ABCDEF";
char *subStr = malloc(4);
memcpy(subStr, &str[3], 3);
substr[3] = 0;

You should also check if the result of the allocation was successful,您还应该检查分配结果是否成功,

char *str = "ABCDEF";
char *subStr = calloc(4, sizeof(char));
if(subStr) memcpy(subStr, &str[3], 3);

You have to terminate the string by adding terminating null-character.您必须通过添加终止空字符来终止字符串。

const char *str = "ABCDEF"; /* use const char* for constant string */
char *subStr = calloc(3 + 1, sizeof(char)); /* allocate one more element */
memcpy(subStr, &str[3], 3);
fprintf(log, "Substring: %s", subStr);

calloc() will zero-clear the buffer, so no explicit terminating null-character is written here. calloc()会将缓冲区清零,因此此处不会写入显式终止空字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM