possible workaround for using strncpy

Posted on 2004-08-25
Last Modified: 2012-08-14
How can I copy a certain number of characters in a string onto another string?

If I have the following:
char fname[20], lname[20], nemp[80],*name,*ptr;
name= Archie S. Andrews  
name[strlen(name)-1]='\0'; // to append to terminate string up to this point
By using strrchr I can point to '.' with the address stored in *ptr, and then copy its contents to lname using strcpy.
But how can I use strncpy in such a way that fname will contain only the string "Archie"?

I have tried the code below:
ptr-=2; // this points to S
strcpy(nemp,ptr); // nemp now contains "S. Andrews"
strncpy(fname,name,(strlen(name) - strlen(nemp));

This code prints out "Archie" but followed by some garbage characters and longer than name. One possible solution to this is to append a '\0' at the end of "Archie".  But what if I do not know the actual length of the first name and I only got it from a file?

If you know of another workaround aside from storing the characters one at a time to another character array, please let me know.  I know that storing it by character is possible, but it will have longer code.  Also, I just wish to use pointers to manipulate strings ^^


Question by:jhen04
  • 3
  • 3
  • 2
  • +2

Expert Comment

ID: 11893126
there are some correction  in ur code
  name= "Archie S. Andrews " // should be enclosed in "
  name[strlen(name)-1]='\0'; // to append to terminate string up to this point
  // you cannot do this with const string pointer. and there is no need for this...

now the solution

memcpy(fname, 0, 20);
ptr = strchr(name, '.');
strncpy(fname, name, (ptr - name - 2 )); // -2 is to move ptr back to <space> after Archie


LVL 22

Expert Comment

ID: 11893258
You could look for the space and replace it with a '\0':

char * p;

p = name;

while( *p != '\0' && *p != ' '  ) p++;

*p = '\0';

LVL 16

Expert Comment

ID: 11893426
I'd use:

char first[20];
char initial[20];
char last[20];

sscanf ( name, "%[^ ] %[^.]. %s", first, initial, last );

The problem with strncpy is that the specified length is the MAXIMUM length it is allowed to build, excluding the terminator. It's more used for limiting the number of characters it copies to the length of the target buffer, avoiding buffer overruns.

sscanf is a much better tool for parsing strings.

LVL 55

Expert Comment

by:Jaime Olivares
ID: 11893700
Specifically to obtain first name, you can simply copy all the name with strcpy and then trim the string at first blank space if needed:

char *pos;

name="Archie S. Andrews";
strcpy(fname, name);          /* copy entire string */
pos = strchr(fname, ' ');       /* search white space */
if (pos) *pos = '\0';    /* cut at this position if found */

Or, if you prefer:

char *pos;
int len;

name="Archie S. Andrews";
pos = strchr(name, ' ');       /* search white space in original string */
len = pos ? pos-name : strlen(name);   /* calculate new len if a white space exists */
strncpy(fname, name,len);          /* copy desired portion */
fname[len] = '\0';    /* ensure a terminating null is appended */

Hope there are not bugs.

Author Comment

ID: 11893799
what if name="Archie Albert Robert S. Andrews" ?

but actually I've found the solution with a few more tweaks in my program.  Thanks for the info though ^^
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.


Author Comment

ID: 11893887
Thanks for the suggestions dear gurus, however I was able to find the solution myself with a few more tweaks on my code.  Thanks for the infos though ^^

char name[80],*ptr,nemp[80],fname[20],lname[20],mi[2];
// ....... some more codes here
if ((ptr=strstr(buffer,"Name="))!=NULL) // get value for Name
      if (name[strlen(name)-1]=='\n')
          name[strlen(name)-1]='\0';  // remove newline character
      strcpy(nemp,ptr-=1); // ptr-- doesn't work!
      strcpy(lname,ptr); // store last name to lname
      fname[0]='\0';      // initialize fname array to NULL
      printf("%s, %s %s.",lname,fname,mi);
LVL 55

Accepted Solution

Jaime Olivares earned 50 total points
ID: 11893930
strcpy(nemp,ptr-=1); // ptr-- doesn't work!

could be:


Author Comment

ID: 11894106

could be:


..... yup this works.  Thanks!

How can I give you some points for this one? ^^  And how do I close this question?
LVL 55

Expert Comment

by:Jaime Olivares
ID: 11894158
You can request to Community Support to reduce the points instead of delete the question.
LVL 22

Expert Comment

ID: 12906376
I'm a bit peeved that my three line answer didnt get it.

 But whatever.


Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode ( They will have you believe that Unicode requires you to use…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use while-loops in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now