4

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?

3
  • 2
    stop using c-style strings in c++ and use the std::string. it has find_first_of or at() which can help you Commented May 29, 2013 at 6:36
  • I need an answer for this example..So in C..Sorry about that Commented May 29, 2013 at 6:36
  • 3
    Removed the c++ tag. Commented May 29, 2013 at 6:37

3 Answers 3

10

Use :

  strncpy ( str2, str1+6, 9);
  str2[9] = '\0';   /* null character manually added */
Sign up to request clarification or add additional context in comments.

Comments

4

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';

Comments

0

Simple way to do that, offset str1:

strncpy ( str2, str1 + 6, 9 );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.