追加字符以获取字符串

ase*_*sel 1 c string

我在C中有以下代码:

    char *str = "Hello World";
    char *s = malloc(strlen(str));
    int i =0;
    for(;i<strlen(str)-5;i++)
    {
        s += *(str+i);
    }
    printf(s);
Run Code Online (Sandbox Code Playgroud)

它没有任何表现.我想要的是获取str存储的子字符串s.

在Java中我会做以下事情:

    String str = "Hello World";
    String s="";

    for(int i=0;i<str.length()-5; i++)
        s+=str[i];

    System.out.println(s);
Run Code Online (Sandbox Code Playgroud)

或者使用substring方法.作为String s = str.substring(1,2);例如.

我怎样才能实现它?

Gre*_*osz 6

使用该strcpy功能.

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

int main(int argc, char *argv[] ) 
{
  char *str = "Hello World";
  size_t length = strlen(str);

  char *s = (char*)malloc(sizeof(char) * (length + 1));

  strcpy(s, str);

  s[length] = '\0'; // makes sure it's NUL terminated

  printf("%s", s);

  free(s);

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

分配目标缓冲区时,请注意字符串终止字符串的事实NUL.

要仅复制子字符串,请使用strncpy:

strncpy(s, str + 6, strlen(str) - 6);
Run Code Online (Sandbox Code Playgroud)

只会将"世界"复制到 s.

在任何情况下,请确保NUL在使用类似函数之前终止C字符串printf.

另见strcatstrncat.好吧,熟悉C数组和指针.


Bri*_*tow 5

其他人已经说过如何正确解决这个问题(strcat),但诀窍是考虑类型.C不会为你做任何神奇的事情.s是char*.当你向char*添加3时会发生什么?你得到另一个char*,它指向更远的3个字符.将'a'添加到char*与向指针添加97(ascii of'a')相同,从而指向远离数组的另一个字符...

我希望能解释发生了什么......