![]() |
|
|||||||
![]() |
|
|
Thread Tools | Display Modes |
|
#1
|
|||
|
|||
|
How to insert a string into string?
I am new programmer in C. I meet a difficult when I write a code " insert a string into a string".
For example: I have a string: "she is 21 old" I want to insert "years" between "21" and "old". (position is 10) Output is : she is 21 years old. This is my code: Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char position, str[100],substr[20];
int i, count ;
printf("-------------------------\n");
printf("Enter a sentence (str): ");
gets(str);
printf("\n Insert a word (substr): ");
gets(substr);
printf("\n Insert word at position (i): ");
gets(i);
for (count = 0; count < strlen(str)-1; count ++)
{
if (count == i)
{
strcat(str,substr);
printf("%s\n", str);
}
}
return 0;
}
Please help me how to fix it, thank so much. Tran Last edited by shabbir; 03-13-2008 at 04:28 AM. Reason: Code block |
|
#2
|
|||
|
|||
|
Hope that I'm not late.. hehe, about that "gets" thing, you cannot use it in a variable which the datatype is not a string. Also, an array of characters is different from a string because in a string, there's a sentinel value at the end of the array which is '\0' and it automatically put at the end if the user enters a sentence or a word while in an array of characters, there's no sentinel value at the end of the array. When would a variable be an array of characters? Well, I'm not sure but maybe when you scan the letters one by one.. And about that string, don't worry, it's not your job to put that NULL thing; it's the work of the computer itself...
My point here is that, you cannot use predefined functions if the variable or any value in the function parameter is different from the one declared in that predefined function... To see the different predefined functions in C, press F1. Hope you understand my lecture.... ![]() Last edited by heavensgate15; 03-18-2008 at 10:16 AM. Reason: there's something wrong in that sentence |
|
#3
|
|||
|
|||
|
Understood not greatly whether you do send to you more articles I to post the box unit or the short news issue I. I want to understand more
Last edited by shabbir; 05-21-2008 at 09:49 PM. Reason: Confine links to signatures |
![]() |
| Thread Tools | |
| Display Modes | |
|
|
|
|||||||||||||||||||||||||||||||||||