• 0

[c] string help


Question

Hi. I wanted to know if it was possible to cut the first part of a string from a substring that I wanted to search. for ex.

string1 = "Here is a sample file."

string2 = "a"

if i wanted to find an occurence of a in string1 i would type:

printf("%s\n", strstr (string1, string2));

this would output "a sample file."

But how would I output the first part? "Here is"

Thanks.

Link to comment
Share on other sites

5 answers to this question

Recommended Posts

  • 0

thanks a lot!

Also, does anybody know if strcpy() would copy over a char * c? or do both arguments have to be char c[100]? And if that is the case how can I get around this? I dont want to have a fixed size. thanks.

Link to comment
Share on other sites

  • 0

saiz66, doesn't seem to me like you understand pointers.

Ya see, the thing is

c[54] is equivalent to *(c+54)

and c is equivalent to , well , c.

The only thing you gotta absopositively make sure, is that you have enough memory allocated.

In c++ google, new + delete, in c google malloc + free

Link to comment
Share on other sites

  • 0
thanks a lot!

Also, does anybody know if strcpy() would copy over a char * c?  or do both arguments have to be char c[100]?  And if that is the case how can I get around this?  I dont want to have a fixed size.  thanks.

Check out the man page on strncpy: http://www.cplusplus.com/ref/cstring/strncpy.html

Both do not have to be the same size. Just make sure dest is at least the size you put in for the 3rd arg. You may want to do something like this for the 3rd arg: sizeof(dest)

Link to comment
Share on other sites

  • 0
Also, does anybody know if strcpy() would copy over a char * c? or do both arguments have to be char c[100]?

char c[100];

c is a char* here too; ie it's a pointer to an array of chars.

The difference is in the memory allocation. If u declare a char*, u're in charge of allocating and deallocating the memory; if u declare a c[100], you don't have to worry about that.

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.