Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 348
  • Last Modified:

How can I copy the string from a specified position in C?

In order to rotate the 2 last charaters in a word, I use the following way
For example, s[] = "Hello";
I would like to copy "lo" to another array with strcpy and then use strcat to concatenate the string "Hel" after "lo" to form "loHel".But I can only copy the whole string to another array, I don't know how to specify an exact position. Thanks, I'm just newbie in C.
0
xiuxiull
Asked:
xiuxiull
  • 2
2 Solutions
 
gj62Commented:
use memcpy...

char orig[] = "Hello"
char newStr[6];

memcpy(newStr, orig[strlen(orig)-2], 3);/* 3 to copy the null*/
memcpy(newStr[2], orig, strlen(orig)-2);
0
 
NosfedraCommented:
since s is actually a pointer, you can use pointer arithmetics to position yourself wherever you want in the string.
Take a look also at strncpy, strncat.

You should do something like:
char buf[20];
strcpy(buf,s+3);
strncat(buf,s,3);
buf[strlen(buf)] = 0; // these are all null-terminated strings so you should end the string with 0.

You have to get familiar with string manipulation routines.

hth...
0
 
gj62Commented:
Whoops, try this:

char orig[] = "Hello";
char newStr[6];

memcpy(newStr, &orig[strlen(orig)-2], 2);
memcpy(&newStr[2], orig, strlen(orig)-2);
newStr[strlen(orig)]=0;
0
 
CleanupPingCommented:
xiuxiull:
This old question needs to be finalized -- accept an answer, split points, or get a refund.  For information on your options, please click here-> http:/help/closing.jsp#1 
EXPERTS:
Post your closing recommendations!  No comment means you don't care.
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now