在C语言中复制字符串的一部分(子字符串)

63

我有一个字符串:

char * someString;
如果我想要这个字符串的前五个字母并将其设置为"otherString",我该如何做?

4
someString 不是一个字符串,它是指向字符串的指针。而且,字符并不一定是字母。在移动字母之前,您需要知道什么是字符串。 - user14554
根据您的需要,最好声明一个大小为6的char数组用于otherstring(5个字节加上一个'\0')。这样,如果您在使用后忘记释放otherstring,就不必担心内存泄漏的问题。 - HeretoLearn
我投票关闭此问题,因为它教导新用户提问的错误方式,甚至投票也应该被禁用。 - Wolf
警告:这个旧问题带来了一大堆非常糟糕的答案,教授危险或不正确/有缺陷的做法。其中一些甚至无法编译。我建议读者避免阅读此帖子,或者向下滚动到我刚刚发布的答案。我还强烈建议打倒所有可怕的答案,特别是那些明显存在错误和编译器错误的答案。 - Lundin
13个回答

-1

一举两得:

char *otherString = strncpy((char*)malloc(6), someString);
otherString[5] = 0;

@pm100 我碰巧同意,但其他人没有表态,所以我觉得这是暗示。 - Steve Emmerson
不要使用strncpy,这是一个错误的建议。请参阅strcpy是否危险,应该使用什么代替?。另外,您没有正确使用它,所以这段代码无法编译。 - Lundin
strncpy缺少第三个参数。 - chqrlie

-1
char largeSrt[] = "123456789-123";  // original string

char * substr;
substr = strchr(largeSrt, '-');     // we save the new string "-123"
int substringLength = strlen(largeSrt) - strlen(substr); // 13-4=9 (bigger string size) - (new string size) 

char *newStr = malloc(sizeof(char) * substringLength + 1);// keep memory free to new string
strncpy(newStr, largeSrt, substringLength); // copy only 9 characters 
newStr[substringLength] = '\0'; // close the new string with final character

printf("newStr=%s\n", newStr);

free(newStr);   // you free the memory 

请使用strncpy替换strcpy,否则会出现太多参数错误。 - Alp Altunel
在将代码发布到SO之前,请先编译它。 - Lundin
将strcpy替换为strncpy:完成 - Cristian

-2

尝试这段代码:

#include <stdlib.h>
#include <stdio.h>
#include <string.h> 

char* substr(const char *src, unsigned int start, unsigned int end);

int main(void)
{
    char *text = "The test string is here";
    char *subtext = substr(text,9,14);

    printf("The original string is: %s\n",text);
    printf("Substring is: %s",subtext);

    return 0;
}

char* substr(const char *src, unsigned int start, unsigned int end)
{
    unsigned int subtext_len = end-start+2;
    char *subtext = malloc(sizeof(char)*subtext_len);

    strncpy(subtext,&src[start],subtext_len-1);
    subtext[subtext_len-1] = '\0';

    return subtext;
}

你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心找到有关如何编写良好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接