Joel
Joel

Reputation: 1

Using strchr to build a string

I have the following:

LPSTR email // Has data in it already
LPSTR index=strchr(email,'@');

Now I want to Insert into a new string:

LPSTR username

the part of "email" from the beginning of the string to "index".

For example: email="[email protected]" so username="roel" .

Is there a function to do it quick or do I need to build one?

Roel

Upvotes: 0

Views: 422

Answers (2)

VenusianKarate
VenusianKarate

Reputation: 61

Email addresses as defined by RFC 5321 are a more complex than your code assumes. For example:

"Strange@Name"@example.com

is a valid e-mail address. If your code has security implications then you'll need something more robust.

Assuming otherwise, strrchr can be used to find the last @ character. Since the domain/address part of an email address cannot contain an @, this will reliably find the @ you're after.

Once you have your index, you have several options in C for string splitting.

If you own the email string buffer and don't need to keep it intact you can split it without the need for any allocations (just make sure you only free email and not username/domain too):

if (index)
{
  *index = '\0';
  username = email;
  domain = index + 1;
}

Or you could split in the same way but use strdup to allocate new string buffers (remember to call free):

if (index)
{
  *index = '\0';
  username = strdup(email);
  domain = strdup(index + 1);
  *index = '@'; /* if you need to use email in full again */
}

If you can't or don't want to modify the email buffer, you can do something like:

if (index)
{
  ptrdiff_t atOffset = index - email;
  username = calloc(atOffset + 1, sizeof(CHAR));
  strncpy(username, email, atOffset);
}

if you're using C++, you should probably use a string encapsulation class instead of C-style string manipulation.

Upvotes: 6

Matthew Flaschen
Matthew Flaschen

Reputation: 284796

size_t indexPos = index - email;
LPSTR username = malloc(indexPos + 1);
memcpy(username, email, indexPos);
username[indexPos] = '\0';

Don't forget to check for index being NULL.

Upvotes: 1

Related Questions