Friday, October 30, 2009

Chap 9[D]d Working with strings is fun

Write a program that extracts part of the given string from the specified position. For example, if the sting is "Working with strings is fun", then if from position 4, 4 characters are to be extracted then the program should return string as "king". Moreover, if the position from where the string is to be extracted is given and the number of characters to be extracted is 0 then the program should extract entire string from the specified position.


void main()
{
char stri[]="Working with string is fun";
char stri2[10];
int a,flag=0,i=0,b;

printf("\nEnter a position for sentence: Working with string is fun");
scanf("%d",&a);

while(flag==0)
{
if(i==(a-1))
{
if(stri[i]==32)
{
i++;
for(b=0;;b++,i++)
{

if(stri[i]==32||stri[i]=='\0')
{
stri2[b]='\0';
break;
}

stri2[b]=stri[i];
}
}

else

for(b=0;;b++,i++)
{

if(stri[i]==32||stri[i]=='\0')
{
stri2[b]='\0';
break;
}

stri2[b]=stri[i];
}
flag=1;
}

i++;
}
printf("\n%s",stri2);
}

11 comments:

  1. can anyone please explain this program???? if the value of a is 4 then how does this gets execute????? please help out .....

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. this program does not ask for how many characters u want!!!

      Delete
  3. i hope this is an alternate way to do this program

    ReplyDelete
  4. #include
    #include
    #include
    void main()
    {
    char s[30];
    int a,j;
    printf("enter the string\n");
    gets(s);
    printf("enter the position for string print\n");
    scanf("%d",&a);
    if(a>0)
    {
    for(j=0;j<a;j++)
    {
    printf("%c",s[(a-1)+j]);
    }
    }
    else if(a==0)
    {
    printf("%s",s);
    }
    }

    ReplyDelete
  5. #include
    #include
    int main()
    {
    char str[100];
    char ans[100];
    int i,j,k;
    printf("enter input\n");
    gets(str);
    printf("enter position to be extracted\n");
    scanf("%d",&i);
    printf("how many\n");
    scanf("%d",&j);
    if(j==0)
    {
    for(k=0;k<=99;k++)
    ans[k]=str[k];
    printf("result is= %s\n",ans);
    }
    if(j!=0)
    {
    for(k=0;k<=j-1;k++)
    ans[k]=str[i-1+k];
    ans[j]='\0';
    printf("result is= %s\n",ans);
    }
    }

    ReplyDelete
    Replies
    1. Could you please explain this

      Delete
    2. In the above program ans[j]='\0' is not required,its of no use

      Delete
  6. CAN I GET THIS PROGRAM IN C++

    ReplyDelete
  7. yess kindly post in c++.

    ReplyDelete