Click here to Skip to main content
15,886,519 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Please I need help with this program.
I am not getting proper result...(The program should find the longest symmetric sub-string and display it)
Thanks for the help.
C#
#include <iostream>
#include<string>
using namespace std;
char s[30];
int i=0, j, first, last, length,subleng, maxi=0;
void main ()
{
    cout<<"Enter a string to process \n";
    cin>>s[i];
    while (s[i]!='\0')
    {

            cin>>s[i];
            i++;
    }
    length = static_cast<int>(strlen(s));
    for(i=0 ; i<length ; i++)
    {
        for(j=length; j>=0; j--)
        {
            if (s[i]==s[j])
            {
                subleng= j-i;
                if(subleng>maxi)
                {
                    first=i;
                    last=j;
                    maxi= subleng;
                }

            }
        }
    }
    cout<<"The longest symmetric substring is : \n";
    for (i=first ; i<last ; i++)
    {

    cout<<s[i];
    }
    cout<<endl<<endl;

}
Posted
Updated 3-May-10 3:13am
v4

Try the following code:

C++
#include <iostream>
#include<string>
using namespace std;
char s[30];
int i=0, j, first, last, length,subleng, maxi=0;
void main ()
{
    cout<<"Enter a string to process \n";
    cin >> s;
    length = static_cast<int>(strlen(s));
    for(i=0 ; i<length ; i++)
    {
        int j,k,n;
        for (n=0; n<2; n++)
        {// 0 => even symmetric substrings, 1 => odd symmetric substrings
          j = i-n;
          k = i+1;
          subleng = n;
          while ( j>=0 && k<length && s[j]==s[k])
          {
            subleng +=2;
            j--; k++;
          }
          if( subleng > maxi)
          {
            first= j + 1;
            maxi= subleng;
          }
        }
    }
    cout<<"The longest symmetric substring is : \n";
    for (i=0 ; i<maxi ; i++)
    {
      cout<<s[first+i];
    }
    cout<<endl<<endl;
}

:)
 
Share this answer
 
Inside the inner for loop you should change if (s[i]==s[j]) to if (s[i]==s[j-1])...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900