• C

Concatenate two strings Last and First Name

I have input coming in as first name and last name.
What I output to screen or file, I would like to format as follows:
lastName,  firstName , for example Doe, John.  Is there a way to do this in C.
 
Is there a string function that would allow me to do.  Are there any examples of this being done?
cookiejarAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Karrtik IyerSoftware ArchitectCommented:
There's a string concatenation method in C.
This is something you can use to achieve the desired output.
The method is strcat.
http://www.tutorialspoint.com/c_standard_library/c_function_strcat.htm
0
phoffricCommented:
>> I would like to format as follows:  lastName,  firstName
Just be careful that your target has enough memory to allow for the concatenation; otherwise you can get crashes (which will be relatively easy to fix); or worse, you just overwrite memory of the object next to your string object. Worse because now you may not detect the problem immediately, and when you do, it may not be obvious that you overwrote memory beyond the bounds of your string array (or allocated memory).
0
Karrtik IyerSoftware ArchitectCommented:
You can even use sprintf.
Something like below.
char first[50]="Joe";
char last[50] = "Dykes" ;
char combined[101] ={} ;//one char extra for accommodating comma
sprintf (combined, "%s, %s", first, last) ;
http://www.cplusplus.com/reference/cstdio/sprintf/
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Get Certified for a Job in Cybersecurity

Want an exciting career in an emerging field? Earn your MS in Cybersecurity and get certified in ethical hacking or computer forensic investigation. WGU’s MSCSIA degree program was designed to meet the most recent U.S. Department of Homeland Security (DHS) and NSA guidelines.  

cookiejarAuthor Commented:
Karrtik, what do I insert between the braces in this statement?

combined[101] ={} ;
0
cookiejarAuthor Commented:
When I use the strcat to concatenate the last and first name, I not sure as to how to add the comma to separate the lastName, firstName.  For example, it look like this, DoeJohn.

How would I include the comma in the destination parameter? I am newbie at C.
0
Karrtik IyerSoftware ArchitectCommented:
You can just say :
char combined[101] ={0} ;
This initialize all the elements in the array to null.
0
Karrtik IyerSoftware ArchitectCommented:
Below is an example on how to use sprintf, inline comments provided for each line.
char* first = "Doe"; //Length  = 3 
			char* last = "John";//Length  = 4
			char* combined = new char[strlen(first) + strlen(last) + 2];/* Combined length is length of first + length of last +1 so total length is 3+4+2 = 9, 2 at end because the char* are null terminated so 1 for comma and 1 for  the null terminator*/
			sprintf(combined,"%s,%s",first, last);

Open in new window

0
Karrtik IyerSoftware ArchitectCommented:
Similar example for strcat is below, I have added inline comments for each line to explain what it does.
			char* first = "Doe"; //Length  = 3 
			char* last = "John";// //Length  = 4 
			const char* commasymbol = ",";//comma symbol, length = 1
			const int combinedlength = strlen(first) + strlen(last) + strlen(commasymbol)+1;// Combined length is length of first + length of last +2 ( length of comma which is 1 +  1 character for Null terminator at the end)
			char* combined = new char[combinedlength];//so total length is 3+4+2 = 9
			memset ( combined, 0, combinedlength );//initialize all elements of the array to NULL (0)
			strcat(combined,first);
			strcat(combined,commasymbol);
			strcat(combined,last);			

Open in new window

0
sarabandeCommented:
to add to above comments:

char* combined = new char[combinedlength];

you normally would use a sufficently big char buffer for concatenation rather than to "spare" some memory and use dynamic memory. the latter is more error-prone and you have to free the buffer after use. so the code without dynamic memory is like

char szFullName[256] = { '\0' };  // use a big buffer. '\0' is a zero byte but 0 also is ok.
strcat(szFullName, "Doe");
strcat(szFullName, ", ");
strcat(szFullName, "John ");

Open in new window


'new' requires a c++ compiler while you asked for c. so in c it would be malloc/free and not new/delete to create and free dynamic buffers.

char * pszFullName = (char *)malloc(strlen(szLastName)+2+strlen(szFirstName)+1);
strcat(pszFullName, szLastName);
strcat(pszFullName, ", ");
strcat(pszFullName, szFirstName);
....
// free buffer after use
free(pszFullName);
// the pszFullName is invalid now

Open in new window


note, if you don't use a dynamic buffer you should make sure that you don't copy beyond buffer size by a check like the following:

void OutputFullName(const char * szLastName, const char * szFirstName)
{
      char szFullName[256] = { '\0' };  // to be safe use a big buffer  
      if (strlen(szLastName) + 2 + strlen(szFirstName) < sizeof(szFullName))
      {
             strcat(szFullName, szLastName);
             strcat(szFullName, ", ");
             strcat(szFullName, szFirstName);
             printf("%s\n", szFullName);
      }
}

Open in new window


Sara
0
Karrtik IyerSoftware ArchitectCommented:
Thanks Sara for point of new and delete being a C++ functionality. It was a miss from my end.
Here is a pure C version of my code which I shared earlier.
1> sprintf version
			char* first = "Doe"; //Length  = 3 
			char* last = "John";// //Length  = 4 
			const char* commasymbol = ",";//comma symbol
			const int combinedlength = strlen(first) + strlen(last) + strlen(commasymbol)+1;// Combined length is length of first + length of last +2 ( length of comma which is 1 +  1 character for Null terminator at the end)
			char* combined =(char *)malloc(combinedlength);
			memset ( combined, 0, combinedlength );//initialize all elements of the array to NULL (0)
			sprintf(combined,"%s,%s",first, last);
			//Do your work			
			//Finally at the end free the memory
			free(combined);

Open in new window

2> strcat version
			char* first = "Doe"; //Length  = 3 
			char* last = "John";// //Length  = 4 
			const char* commasymbol = ",";//comma symbol
			const int combinedlength = strlen(first) + strlen(last) + strlen(commasymbol)+1;// Combined length is length of first + length of last +2 ( length of comma which is 1 +  1 character for Null terminator at the end)
			char* combined =(char *)malloc(combinedlength);
			memset ( combined, 0, combinedlength );//initialize all elements of the array to NULL (0)
			strcat(combined,first);
			strcat(combined,commasymbol);
			strcat(combined,last);			
			//Do your work			
			//Finally at the end free the memory
			free(combined);

Open in new window

0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C

From novice to tech pro — start learning today.

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.