dali1985
dali1985

Reputation: 3313

how to get a part of a char array in c

I am new in C and I have the following simple code. I know that with the strncpy I can copy characters from string.

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

int main ()
{
  char str1[]= "To be or not to be";
  char str2[40];

  strncpy ( str2, str1, 5 );
  str2[5] = '\0';   /* null character manually added */
  puts (str2);

  return 0;
}  

The output of this code is

To be

If I want the result to be ´or not to´ how can I read these characters? From 7-15 in this case?

Upvotes: 4

Views: 32879

Answers (3)

Dayal rai
Dayal rai

Reputation: 6606

No need to count manually ,you can use standard library function for this.Try like following

strncpy ( str2, str1+strlen("To be "), strlen("or not to") );
str2[strlen("or not to")] = '\0';

Upvotes: 4

Vijay
Vijay

Reputation: 67221

Use :

  strncpy ( str2, str1+6, 9);
  str2[9] = '\0';   /* null character manually added */

Upvotes: 10

Bart Friederichs
Bart Friederichs

Reputation: 33511

Simple way to do that, offset str1:

strncpy ( str2, str1 + 6, 9 );

Upvotes: 0

Related Questions