I have the following code in C:
char *str = "Hello World";
char *s = malloc(strlen(str));
int i =0;
for(;i<strlen(str)-5;i++)
{
s += *(str+i);
}
printf(s);
It shows nothing. What I want is to get the substring of str stored in s.
In Java I would do the following:
String str = "Hello World";
String s="";
for(int i=0;i<str.length()-5; i++)
s+=str[i];
System.out.println(s);
Or instead use the substring method. As String s = str.substring(1,2); for example.
How can I achieve it?
Use the
strcpyfunction.When allocating the destination buffer, pay attention to the fact that strings are terminated by the
NULcharacter.To only copy a substring, use
strncpy:will just copy “World” into
s.In any case, make sure your C strings are
NULterminated before using functions likeprintf.See also
strcatandstrncat. And well, familiarize yourself with C arrays and pointers.