Google Answers Logo
View Question
 
Q: C programming question ( Answered 4 out of 5 stars,   0 Comments )
Question  
Subject: C programming question
Category: Computers > Programming
Asked by: derekwtp-ga
List Price: $10.00
Posted: 23 Feb 2003 17:58 PST
Expires: 25 Mar 2003 17:58 PST
Question ID: 166174
I am in need of help w/ my assignment. More or less in the area of
understanding it in order to complete it, not just complete it but
understanding.


You must write the following 4 functions and a driver to test them.
But I have done 1 and 2 already, and they are in the Code directory.
You just have to do 3 and 4, really.

You are not allowed to use standard C string functions, with the
exception of strcpy( ) in your main driver, and strlen( ) in the
actual functions. For extra credit, you may write your own version of
strlen( ) and use it here.

   1. Write a function called findstring( ) which will take as
arguments two strings (pointer to char) and return the integer
corresponding to the location in the first string where the first
occurance of the second string begins. If the second string does not
appear in the first string, return -1
   2. Write a function called removestring( ) which will take as
arguments a string, and two integers. The firsts integer is the
location of the first char to be removed, and the second integer is
the number of characters to remove.
   3. Write a function called insertstring( ) which will take as
arguments two strings and an integer. The second string is to be
inserted into the first string begining at the position specified by
the integer.
   4. Write a function called replacestring( ) which will take as
arguments three strings(source,s1,s2). The function will replace the
first occurance of s1 in source with s2. Please note that s1 and s2 do
not need to be the same length. Use findstring( ), removestring( ),
and insertstring( ) to do this.


I am still having trouble deciphering what this functionis doing. 

int findstring(char *s1,char *s2)
{
  char *p1=s1,*p2=s2,*tmp;

  do {
    while ((*p1 != *p2)&&(*p1 != '\0')) p1++;
    tmp = p1;
    while ((*tmp == *p2)&&(*tmp != '\0')) {
      tmp++;
      p2++;
    }
    if (*p2 == '\0') return(p1-s1);
    else {
      p2 = s2;
      p1++;
    }
  }
  while (*(p1-1) != '\0');
  return(-1);
}


I dont know why incrementing char strings are what you want to do? or
are you incrementing values in an array? The latter makes sense but i
dont see how it makes sense?

Request for Question Clarification by jeanluis-ga on 23 Feb 2003 18:21 PST
Hello,
I am not really sure exactly what you are looking for first you say
you need help understanding the assignment. Then you say "You just
have to do 3 and 4, really". Then you ask about string arithmetic. So
I am not really sure what you want. But here is the answer to the
string arithmetic question:

If you have a char* tmp, and tmp is pointing to a string (actually it
could be pointing to anything... but lets say it is pointing to a
string) and you perform the operation: tmp++; what you are doing is
incrementing the address that tmp points to. In otherwords lets say
tmp points to the start of the string "Hello world" (i.e. tmp points
to the address of the 'H') and you perform the tmp++; operation, tmp
will then point to the 'e'. Here is an example:

{ 
printf("%s\n", tmp);
tmp++;
printf("%s\n", tmp);
}

The output of that code if tmp initially pointed to the "Hello world"
string would be:

Hello world
ello world

Additionally if you performed the operation tmp--; it would decrement
the address tmp points to and tmp would again point to the 'H' in
"Hello world".

In general this is called pointer arithmetic, and all C mathamatical
operations can be performed on pointers. For example you could do the
following to out friend tmp: tmp += 6; which would cause tmp to point
to the start of the word world.

To learn more about pointers what I have found works very well is to
write code with a good debugger (i.e. MS VC++) and just "play" with
pointer arithmetic and single step all the code with your pointers in
the watch window and just see what different operations do to the
pointers and try to figure out why things act the way they do.

Hopefully this helps, let me know if you want more info, or if you
have other questions, or if this is an acceptable answer.
--jld

Clarification of Question by derekwtp-ga on 24 Feb 2003 08:43 PST
I am sorry. Yes you are correct I am to right functions 3 and 4.
Functions 1 and 2 are already written and they are:

void removestring(char *s,int i,int n)
{
  char *p=s+i;
       
  do {
    *p = *(p+n);
        if (*p != '\0') p++; /* only bump pointer if not finished */
              }

              
  while (*p != '\0');
  
}



int findstring(char *s1,char *s2)
{
  char *p1=s1,*p2=s2,*tmp;

  do {
    while ((*p1 != *p2)&&(*p1 != '\0')) p1++;
    tmp = p1;
    while ((*tmp == *p2)&&(*tmp != '\0')) {
      tmp++;
      p2++;
    }
    if (*p2 == '\0') return(p1-s1);
    else {
      p2 = s2;
      p1++;
    }
  }
  while (*(p1-1) != '\0');
  return(-1);
}


Now I am working on insertstring.c the third function. thank you for
your reply earlier. In the midst of understanding, i have moved into
another questionable area..:

void insertstring(char *first,char *second,int number)
{
char temp[80];

     temp= first + number; <---why doesn't this work
     char *temp= first + number; <------ but this works

}
Answer  
Subject: Re: C programming question
Answered By: jeanluis-ga on 24 Feb 2003 10:08 PST
Rated:4 out of 5 stars
 
Ok the reason the array technique above does not work is becuase
temp[80] is not a pointer. Rather it is an array of length 80. It is
very important to remember that in order to do pointer math you must
be dealing with pointers.

char temp[80]; 
temp = first + number; <---why doesn't this work 

To get the desired results try something like this:

char temp[80];
memcpy(temp, first+number, strlen(first) - number + 1); /* Note: You
could also use a strcpy() here, Ex: strcpy(temp, first+number);*/

the above memcpy will copy the string that starts at first+number to
the temp array. If you use this technique then after you have inserted
the string into the temp array you should make the first pointer point
to the start of the temp array which can easily be done as follows:
first = temp;

Hopefully this helps, please let me know if you want more info, or if
you have any other questions.
       --jld

Clarification of Answer by jeanluis-ga on 24 Feb 2003 10:21 PST
BTW: I think I should tell you that performing the following
operation:
first = temp; 
at the conclusion of your function might not be the best way to update
the first pointer, because it may cause a memory leak. It is hard for
me to say, without seeing the code that calls the insertstring()
function. It may be better to copy the data in the temp array to the
address first points to instead as follows:
strcpy(first, temp);
If you do that however you have to be sure that first points to a
buffer that is big enough to hold the whole temp string. Based on what
I currently know about the assignment it is impossible for me to
advise you one way over the other.
Anyhow I just wanted to bring that to your attention, if you need more
help with this or anything else please let me know.
--jld

Request for Answer Clarification by derekwtp-ga on 24 Feb 2003 12:24 PST
Sorry, My main is just being used as a driver to test out the
individual function. I am not however getting desired results. This is
what I have


main()
 {
 void removestring(char*,int,int);
 int findstring(char*,char*);
 void insertstring(char*,char*,int);


 char beacon[80];
 char bread[80];
 int x;

 strcpy(beacon,"Derek Winchester");
 strcpy(bread," Steven");

 insertstring(beacon,bread,5);
 
}

int findstring(char *s1,char *s2)
{
  char *p1=s1,*p2=s2,*tmp;

  do {
    while ((*p1 != *p2)&&(*p1 != '\0')) p1++;
    tmp = p1;
    while ((*tmp == *p2)&&(*tmp != '\0')) {
      tmp++;
      p2++;
    }
    if (*p2 == '\0') return(p1-s1);
    else {
      p2 = s2;
      p1++;
    }
  }
  while (*(p1-1) != '\0');
  return(-1);
}



void removestring(char *s,int i,int n)
{
  char *p=s+i;
       
  do {
    *p = *(p+n);
        if (*p != '\0') p++; /* only bump pointer if not finished */
              }

              
  while (*p != '\0');
  
}

void insertstring(char *first,char *second,int number)
{
int tempnum = strlen(second);
char *temp= first + number;
int i;

while (*second != '\0')
{
*(temp+tempnum) = *(temp); 
*temp = *second;
*temp++;
*second++;

 }


printf ("%d\n",tempnum);
printf ("%s\n",temp);
printf ("%s\n",first);
printf ("%s\n",second);




}                                        


here is my output: 

[root@win186821wks six]# ./six
7
 Winche??
Derek Steven Winche??

[root@win186821wks six]# ./six
7
 Winche??
Derek Steven Winche??

[root@win186821wks six]# ./six
7
 Winche??
Derek Steven Winche??

[root@win186821wks six]# ./six
7
 Winche??
Derek Steven Winche??

[root@win186821wks six]# ./six
7
 Winche??
Derek Steven Winche??

[root@win186821wks six]# cc *.c -o six
[root@win186821wks six]# ./six
7
 Winche??
Derek Steven Winche??

[root@win186821wks six]#


What do the question marks mean?

Clarification of Answer by jeanluis-ga on 24 Feb 2003 15:46 PST
Hmm.... Well the strange chars at the end of your strings show up
becuase the strings you are printing do not have a NULL char at the
end of them... so printf just keeps on printing until it reaches a
random NULL in memory.

I see what you are tring to do, and it will almost work. The basic
point that you are missing is the fact that you really need to break
it up into 2 loops. One loop to copy the end of first to its new
position in the string, and a second loop to copy second into its
position. You could do it with one loop, but it would be (IMHO) not
optimal, and require at least one if/then/else statement.


Here are some thoughts, I assume that first will always be large
enough to hold the whole resulting string. So the general algorithm I
would use is this:
1) Create a temp string array (not a pointer) that is big enough to
hold the final result (i.e. the same size as first)
2) copy number chars from first into the temp string
3) copy second into temp+number (or temp[number] because it is an
array)
4) copy first+number into temp+number+strlen(second). Make sure you
either copy the null terminator from first, or add a null yourself as
follows:
temp[number+strlen(second)+1] = 0;
5) then just copy the temp string into first and call it quits :)

I hope this helps, I didn't write the function for you because I think
you will learn more by banging out the details yourself. But the above
outline should get the required results. If you wanted to optimize it
then you could do it without using a temp array and do it "in place"
by maniuplating the first string. (Which is what you are attempting to
do already :)

But my advice on something like this is just get it to work, then once
you have it and understand it, then optimizing it is much easier.

Anyhow as always, just let me know if you have any other questions.
--jld

Request for Answer Clarification by derekwtp-ga on 24 Feb 2003 17:31 PST
Man jld!! I wish i got your email an hour earlier : ) no worries I
banged around and ended up w/ this

void insertstring(char *first,char *second,int number)
{
int tempnum = strlen(second);
char *temp= first + number;
int i;

while (*second != '\0')
{
*(temp+tempnum) = *(temp);
*temp = *second;
*temp++;
*second++;

 }

Which seems similar to what you were saying..at least to me it did. Do
you see any problems with it? Also I am trying to make this optimal or
at least functional it is the last function, but for some reason
common logic is not agreeing w/ me.

In work copy:

void replacestring (source,s1,s2)
{

int length1= strlen(s1);
int length2= strlen(s2);
int x= findstring(source,s1);
int rem_characters=x+length2;

insertstring(source,s2,x);


removestring(source,rem_characters,length1);

printf ("%i\n",x);
printf ("%s\n",source);
}

Request for Answer Clarification by derekwtp-ga on 24 Feb 2003 18:44 PST
Okay this is where I am stuck. You have the other functions this is my
last function:

void replacestring (source,s1,s2)
{

int length1= strlen(s1);
int length2= strlen(s2);
int x= findstring(source,s1);
int rem_characters=x+length2;

insertstring(source,s2,x);


removestring(source,rem_characters,length1);

printf ("%d\n",length1);
printf ("%d\n",length2);
printf ("%d\n",rem_characters);
printf ("%i\n",x);
printf ("%s\n",source);
}



However it is not working like I hope it would. Here is my output:

[root@localhost six]# ./six
3341
 twor all and all for one
[root@localhost six]# cc *.c -o six
replacestring.c: In function `replacestring':
replacestring.c:6: warning: passing arg 1 of `strlen' makes pointer
from integer without a cast
replacestring.c:7: warning: passing arg 1 of `strlen' makes pointer
from integer without a cast
[root@localhost six]# ./six
3
3
4
1
 twor all and all for one
[root@localhost six]#
 


and as you can see I am getting warning during compilation. Your help
would be appreciated..

-Derek

Clarification of Answer by jeanluis-ga on 24 Feb 2003 18:47 PST
Sorry about not getting back to you faster, you cought me at a bad
time I was just leaving work when I get the note that said I had a
clarification req. Anyhow:
The function that you "ended up" with appears to be exactly the same
as the one you started with?! Hopefully you accidently posted the
wrong code. :)
It should also be noted that your replacestring() function appears to
work. I have actually compiled it with gcc (along with your other
functions) and executed it, it seems to work perfectly. Do note,
however, that I do have a working copy of insertstring() and that the
insertstring() function that you listed does not seem to work as we
discussed before.

I advise going back to insertstring and making sure that it in fact
works properly.

:) Let me know if you have any other problems.
--jld

Clarification of Answer by jeanluis-ga on 24 Feb 2003 18:57 PST
I just noticed that you posted 2 R4Q's here is what is causing the
warnings. Your function prototype does not specify the type of the
arguments. As such gcc assumes int, which in this case is wrong (it
should be char*). In my last post I assumed that you were posing
shorthand code, and that you actually have the prototype correct.
Anyhow fixing the function decl will clear up those warnings.
Unfortunately the replacestring() function you posted still works for
me either way. Which causes me to believe that the insertstring()
function may still be at fault. I still advise a double check of
insertstring().

Let me know if you have anymore problems. :)
--jld
derekwtp-ga rated this answer:4 out of 5 stars
was a great help

Comments  
There are no comments at this time.

Important Disclaimer: Answers and comments provided on Google Answers are general information, and are not intended to substitute for informed professional medical, psychiatric, psychological, tax, legal, investment, accounting, or other professional advice. Google does not endorse, and expressly disclaims liability for any product, manufacturer, distributor, service or service provider mentioned or any opinion expressed in answers or comments. Please read carefully the Google Answers Terms of Service.

If you feel that you have found inappropriate content, please let us know by emailing us at answers-support@google.com with the question ID listed above. Thank you.
Search Google Answers for
Google Answers  


Google Home - Answers FAQ - Terms of Service - Privacy Policy