• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 574
  • Last Modified:

possible workaround for using strncpy

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));
printf("%s",fname);

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

Thanks

0
jhen04
Asked:
jhen04
  • 3
  • 3
  • 2
  • +2
1 Solution
 
nrohanCommented:
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


-Rohan

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

char * p;

p = name;

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

*p = '\0';

0
 
PaulCaswellCommented:
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.

Paul
0
What Kind of Coding Program is Right for You?

There are many ways to learn to code these days. From coding bootcamps like Flatiron School to online courses to totally free beginner resources. The best way to learn to code depends on many factors, but the most important one is you. See what course is best for you.

 
Jaime OlivaresSoftware ArchitectCommented:
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.
Jaime.
0
 
jhen04Author Commented:
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 ^^
0
 
jhen04Author Commented:
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
{
    ptr+=5;
    strcpy(name,ptr);
      if (name[strlen(name)-1]=='\n')
          name[strlen(name)-1]='\0';  // remove newline character
      ptr=strrchr(name,'.');
      strcpy(nemp,ptr-=1); // ptr-- doesn't work!
      ptr+=3;
      strcpy(lname,ptr); // store last name to lname
      fname[0]='\0';      // initialize fname array to NULL
      strncat(fname,name,(strlen(name)-strlen(nemp)));
      mi[0]='\0';
      strncat(mi,nemp,1);
      printf("%s, %s %s.",lname,fname,mi);
}
0
 
Jaime OlivaresSoftware ArchitectCommented:
strcpy(nemp,ptr-=1); // ptr-- doesn't work!

could be:

strcpy(nemp,--ptr);
0
 
jhen04Author Commented:

could be:

strcpy(nemp,--ptr);


..... yup this works.  Thanks!

How can I give you some points for this one? ^^  And how do I close this question?
0
 
Jaime OlivaresSoftware ArchitectCommented:
You can request to Community Support to reduce the points instead of delete the question.
0
 
grg99Commented:
I'm a bit peeved that my three line answer didnt get it.

 But whatever.

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

What Kind of Coding Program is Right for You?

There are many ways to learn to code these days. From coding bootcamps like Flatiron School to online courses to totally free beginner resources. The best way to learn to code depends on many factors, but the most important one is you. See what course is best for you.

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