CrazyEngineers
  • Problem with substring program

    Updated: Oct 26, 2024
    Views: 1.3K
    hello friends,

    I wrote a c program to perform the substring operation on the string str[100]. This program was to take the position index pos and the number of characters len that needs to be printed on the screen. variable length stores the length of the string str[100].

    Although I am getting the correct output from this program yet, I get additional characters after my output text. Please help me with this situation.

    Here is the program that I have coded:-

    #include<stdio.h>//extra ouput
    void main()
    {
    char str[100], subs[100];
    int len,length = 0, pos,i = 0,j = 0;
    printf(" enter the string\n");
    gets(str);
    printf(" enter the position\n");
    scanf("%d", &pos);
    printf(" enter the length\n");
    scanf("%d", &len);
    for( i = 0; str != '\0'; i++)
    length++;
    i=0;
    if((pos+len-1) > length)
    printf("invalid query terminating...\n");
    else
    {
    i = pos;
    for(j = 0; j<len; j++)
    {
    subs[j] = str;
    i++;
    }
    }
    printf("\n\n displaying the result\n\n");
    i = 0;
    puts(subs);
    }

    this program produces extra characters like ?^ at the end of the output text.
    0
    Replies
Howdy guest!
Dear guest, you must be logged-in to participate on CrazyEngineers. We would love to have you as a member of our community. Consider creating an account or login.
Replies
  • Shalini051

    MemberMay 7, 2013

    Hi,
    You have not terminated the substring(subs) after extracting it from the original string(str).Thats why the junk characters.....
    Are you sure? This action cannot be undone.
    Cancel
  • rahul69

    MemberMay 8, 2013

    proffy
    hello friends,
    this program produces extra characters like ?^ at the end of the output text.
    First of all, it is better to put your code in [ code ] tags as it helps in reading the code,
    Now coming to your code:
    You should add a null character after the creation of substring.
    This should solve your problem, but if u still face some problem, we are happy to help👍😁...
    Are you sure? This action cannot be undone.
    Cancel
Home Channels Search Login Register