[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now


possible workaround for using strncpy

Posted on 2004-08-25
Medium Priority
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
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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.


Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

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 ^^

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 200 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

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
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.
Suggested Courses

649 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