Jump to content

String insertion in C as part of a string and pointer tutorial

- - - - -

  • This topic is locked This topic is locked
11 replies to this topic

#1
Yuriy M

Yuriy M

    Learning Programmer

  • Members
  • PipPipPip
  • 70 posts
Hi guys. It's been a while since I last posted here.

I'll cut straight to the chase. I've been brushing up on my C programming for the past year and have been working through an old textbook. One of the questions in that textbook asks the following:

Write a program that inserts one string into another. The program should prompt the user for a string. Then the program should prompt the user to enter another string that is to be inserted into the first string. Finally, the program should prompt the user for the position at which to insert the second string. The program should then do the insertion and display the new string. For example, suppose that the user enters for the first string "I left heart in Francisco", for the second string, "San ", and for the position, 16. Then the program should output "I left heart in San Francisco".

Here is the program that I've written up:

/* Program 12-9 */


#include <stdio.h>


main()

{

      /* Declare variables */

      

      char string[100],            /* The string to be inputted by the user */

           insert[100],            /* The string to be inserted into the other string */

           inserted[200] = {' '},  /* The resulting string after insertion */

           * str_ptr = string,     /* The pointer to the string array */

           * ins_ptr = insert,     /* The pointer to the insert array */

           * instd_ptr = inserted; /* The pointer to the inserted array */

      int  position,               /* The specific position for the second string to be inserted into the first */

           string_count = 0;       /* Counts the characters in the string */

      

      /* Prompt the user for the first string */

      

      printf("\nEnter a string: ");

      gets(string);

      

      /* Prompt the user for the second string to be inserted into the first */

      

      printf("\nEnter a string to be inserted into the first string: ");

      gets(insert);

      

      /* Prompt the user for the position of the second string to be inserted */

      

      printf("\nEnter the numerical position of the string to be inserted into the first string: ");

      scanf("%d", &position);

      

      /* Check both strings and insert the second string into the specific position */

      

      while (*instd_ptr != '\0')

      {

       while (*str_ptr != '\0')

       {

        if (string_count == position)

        {

         while (*ins_ptr != '\0')

         {

          *instd_ptr = *ins_ptr;

          ++ins_ptr; 

          ++instd_ptr;  

          ++string_count;

         }

        }

        *instd_ptr = *str_ptr;

        ++str_ptr;

        ++instd_ptr;  

        ++string_count;

       }

      }

       

      /* Display the results */

      

      printf("\nHere is the result of your insertion: ");

      printf("%s", inserted);

      printf("\n");

}

I've tested the program out by inserting the second string at the very beginning, middle, and end of the first string. The program question expects you to also leave a space after you type in the second string so it would make for easier string placement. However, it shows me an example of putting one string in the middle of another. What I want to know is if the last character(s) inputted as a space in the first string is applicable for putting in the second string?

Let's say for instance that I just type in "I left heart in San" as the first string and "Francisco" as the second string. As the rules state, I have to put "Francisco" in a specific position within "I left heart in San". The position I want is two spaces after "San". If I just type in "I left heart in San" and chose position 20, the program would just output it as "I left heart in San" and ignore "Francisco" as a result of the NULL character after "n". However, if I type in "I left heart in San ", the program will definitely put in "Francisco" because there is an existing character placement in position 20 which is the blank space. As long as there isn't a NULL character prior to that space, all I need is one character "F" to fill that space and the program will print out "Francisco" without any problems.

I also want to point out that such functions like strncat(), strcat() and strlen() are not supposed to be used just yet. They would be covered in the next chapter of my textbook. Basically, the author just wants to see if I can even get a program working using the limitations that I have now.

So, I just want to ask is if the code that I typed sufficient enough to meet that question's requirements?
For $1000: Something that is a miserable pile of secrets.

#2
Yuriy M

Yuriy M

    Learning Programmer

  • Members
  • PipPipPip
  • 70 posts
Well, if nobody is going to reply, then I'll just have to assume that the program is completed and move on.
For $1000: Something that is a miserable pile of secrets.

#3
karthik

karthik

    Newbie

  • Members
  • Pip
  • 1 posts
Fantastic JOb!!:c-thumbup:
this helped me to complete my project
thank you very much

#4
jcampos8782

jcampos8782

    Learning Programmer

  • Members
  • PipPipPip
  • 49 posts
The only problem that I could see is that you are representing the strings as finite length arrays instead of pointers to char. If you represent them as pointers to char, then you will not be forced to stick within a set size requirement.


      char string[100],            /* The string to be inputted by the user */

           insert[100],            /* The string to be inserted into the other string */

           inserted[200] = {' '},  /* The resulting string after insertion */

           * str_ptr = string,     /* The pointer to the string array */

           * ins_ptr = insert,     /* The pointer to the insert array */

           * instd_ptr = inserted; /* The pointer to the inserted array *



Instead, try something like this:
      

           char* string1 = &string1;

           char* string2 = &string2; 

           int insertAt = someInt; 


Then all you have to do is increment the pointers and remember that every string is terminated by the null character (\0) and remove the null character from string 2.

#5
Yuriy M

Yuriy M

    Learning Programmer

  • Members
  • PipPipPip
  • 70 posts

karthik said:

Fantastic JOb!!:c-thumbup:
this helped me to complete my project
thank you very much
Good to see that you're all smiles but don't go overboard. Part of the process of being a great programmer is coming up with various ways yourself to get your program working in the most efficient manner. Don't just copy and paste from forums.

JCampos8782, thanks for the advice but the example you provided just gives me compile-time errors. I've already modified my program to have it provide the best result possible and it doesn't violate any C programming rules because it follows the guidelines that the author intended in my textbook.

Edited by Yuriy M, 01 March 2011 - 07:53 PM.
Clarification

For $1000: Something that is a miserable pile of secrets.

#6
rocketboy9000

rocketboy9000

    Learning Programmer

  • Members
  • PipPipPip
  • 79 posts
Ok, but now try to insert the second string directly into the first, without creating a third.

#7
Yuriy M

Yuriy M

    Learning Programmer

  • Members
  • PipPipPip
  • 70 posts

rocketboy9000 said:

Ok, but now try to insert the second string directly into the first, without creating a third.
When you mean by "without creating a third", do you mean outputting the results of two merged strings into a third string or inserting the contents of the second string into the first from a temporary storage string?
For $1000: Something that is a miserable pile of secrets.

#8
Yuriy M

Yuriy M

    Learning Programmer

  • Members
  • PipPipPip
  • 70 posts
Ok, so after doing some fiddling, I was able to come up with a program that doesn't require the use of a third string in order to insert one string into another:

#include <stdio.h>

main()
{
      /* Declare variables */
      
      char string1[100],           /* The first string */
           string2[100],           /* The second string */
           *str_ptr1 = string1,    /* Pointer to the first string */
           *str_ptr2 = string2;    /* Pointer to the second string */

      int  position = 0,           /* The specific position for the second string to be inserted into the first */
           string_count = 0;       /* Counts the characters in the string */
      
      /* Prompt the user for the first string */
      
      printf("\nEnter a string: ");
      gets(string1);
      
      /* Prompt the user for the second string to be inserted into the first */
      
      printf("\nEnter a string to be inserted into the first string: ");
      gets(string2);
      
      /* Prompt the user for the position of the second string to be inserted */
      
      printf("\nEnter the position of the string to be inserted into the first string: ");
      scanf("%d", &position);
      
      /* Check both strings and insert the second string into the specific position */        
      
      printf("\nHere is the result of your insertion: ");
      
      while (*str_ptr1 != '\0')
      {
       if (string_count == position)
       {
        while (*str_ptr2 != '\0')
        {
         putchar(*str_ptr2);
         str_ptr2++;
        }
       }
       putchar(*str_ptr1);
       str_ptr1++;
       string_count++;
      }
      printf("\n");
}

For $1000: Something that is a miserable pile of secrets.

#9
Xupicor

Xupicor

    Learning Programmer

  • Members
  • PipPipPip
  • 46 posts
int main()!
By the way, do you find one space indenting readable? :)

#10
Yuriy M

Yuriy M

    Learning Programmer

  • Members
  • PipPipPip
  • 70 posts
The development environment that I use doesn't require the "int" data type for the main() function but thanks for noticing. :)

And one space indenting is readable to me.
For $1000: Something that is a miserable pile of secrets.

#11
Xupicor

Xupicor

    Learning Programmer

  • Members
  • PipPipPip
  • 46 posts
For what I can remember, hosted implementations do force you to have int, but in C89 you could leave out the type of a function and it would be assumed to be int. Then again C89 had things "a bit strange" if you ask me. C99 fixed at least some of them.
But maybe you're working on a freestanding one?

If it's readable for you, well, each to his own. I find 2 to be a minimum to be readable, and 3-4 to be comfortable. ;)

edit: Also, what will happen if I run your app and just "type away"? I mean, it'll want me to type a string, right? What if I type 300 chars long text in it? Or 3000?
hint: gets(string1);

#12
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,118 posts
  • Location:Vancouver, Eh! Cleverness: 200
Something to remember: The assembled programs have no awareness of data types, it is purely for the compiler to provide the proper calls in the assembled program to work with the said data type. You can freely return char main(), for one byte of return values 0-127, unsigned long long main() if the operating system can actually use or benefit from the size. C89 does not recognise superfluous data type of main, c99 warns that no data type will default to int only because main can be assumed to always return a numeric below integer maximum. The default could easily have been int16 main in the standard if it was not assumed there would be more than the 32 thousand return values.
Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users