Connecting Tech Pros Worldwide Forums | Help | Site Map

how to copy a pointer string into a normal string which is of type "char"

Newbie
 
Join Date: Jun 2008
Posts: 7
#1: Jul 22 '08
please help me out in this regard as this is urgent to me because i stuck in the middle of a program.......
here I have a program like this......


char name[]="rajesh";
char *x=strchr(name,"j");
int k =strlen(name);
int i=x-name;
int p=k-i;


here I want to copy the string "jesh" into name[]..because i want 2 make it in loop....


so i have written like this...

name=&x[p];

I know here the name[] is not of pointer type so it is not working...

please help me....
and I have one more doubt here. can we write strchr(name,'s'); where name is of pointer type....
gpraghuram's Avatar
Expert
 
Join Date: Mar 2007
Location: Chennai
Posts: 1,258
#2: Jul 22 '08

re: how to copy a pointer string into a normal string which is of type "char"


You can achive the same like this

Expand|Select|Wrap|Line Numbers
  1. int main()
  2. {
  3.     char arr[] = "abcdef";
  4.     printf("%s\n",arr);
  5.     sprintf(arr,"%s",(arr+2));
  6.     printf("%s\n",arr);
  7. }
  8.  
  9.  
You can use this logic with strchr to determine the start position

Raghu
ashitpro's Avatar
Expert
 
Join Date: Aug 2007
Posts: 389
#3: Jul 22 '08

re: how to copy a pointer string into a normal string which is of type "char"


First of all...
I'd like to remind you that 'name' is character array...You can not change base address of any array.
So "name=&x[p];" this statement is invalid...
If name was character pointer then it would have worked.
If you don't want it as character pointer..simply use for loop and copy the desired string.

Regarding your second question...you can have character pointer as your first arg to strchr..provided that it is null terminated....
Needs Regular Fix
 
Join Date: Jul 2008
Posts: 383
#4: Jul 22 '08

re: how to copy a pointer string into a normal string which is of type "char"


Quote:

Originally Posted by prasad8619

here I want to copy the string "jesh" into name[]..because i want 2 make it in loop....

I don't get it. Do you want to use two loops?
As x points to character within name, and x itself is a string, ewe can't use strcpy(name,x); Use memmove() instead as it's guaranteed to work with overlapped areas.


Quote:
and I have one more doubt here. can we write strchr(name,'s'); where name is of pointer type....
Yes.
Newbie
 
Join Date: Jun 2008
Posts: 7
#5: Jul 22 '08

re: how to copy a pointer string into a normal string which is of type "char"


Iam very much thankful to all who helped me in solving this problem.....


I did it using "for loop" only....


Here I came to know one new thing that is while using pointer in "strchr" that should be terminated with "null" character...

Thanks alot......the second one helped me alot in writing my program......
Reply