Hi there,i have to create a program that shows the symbolic derivative of a polynomial function, and my teacher told that it is all about string manipulation,but i cant find find any valid tutorial or something that shows me how to do it.i've checked but what i have found is those simple manipulation like adding sting, comparing, etc. Can you advise me any web page or book that can help me?

Dani AI

Generated

laid out the right decomposition (tokenize → numeric term → termwise derivative → render). The sample code posted by shows common syntax and type problems and a brittle parsing approach; the checklist and example below explain practical fixes and a more robust path. is right that std::string has many helpers, but for real-world input a small tokenizer or a regex-based scanner is usually safer than ad-hoc substr indices.

Common problems to fix (visible in the posted snippet)

  • Syntax errors: missing semicolons, missing or wrong headers, and functions used before they are declared.
  • Wrong return types / signatures: parsing should return a structured term (coefficient+exponent) or a container, not an int or char.
  • Scope and names: avoid reusing the same stringstream name or using variables that are not in scope.
  • Expression bugs: don't use the comma operator when forming a pair; compute coef*exp and return a proper pair/object.
  • Parsing brittleness: fixed substr offsets break for variable-length terms and duplicate exponents (e.g. 2x^5+3x^5 needs combining).

A practical, robust approach

  • Tokenize by signs (keep the sign with each term) or use a regex to extract sign, optional numeric coefficient, optional variable, and optional exponent.
  • Accumulate terms into a map from exponent → coefficient to combine like terms before/after differentiation.
  • Derivative rule: newCoef = coef * exp; newExp = exp - 1; drop zero coefficients; format carefully (omit 1x as x, omit ^1, show constants).

Example parsing sketch (C++11+)

#include <regex>
#include <string>
#include <map>

std::regex term_re(R"(([+-]?)\s*([0-9]*\.?[0-9]+)?\s*([a-zA-Z])?(?:\^([+-]?\d+))?)");

std::map<int,double> collect_terms(const std::string& s) {
  std::map<int,double> M;
  for (std::sregex_iterator it(s.begin(), s.end(), term_re), end; it != end; ++it) {
    auto m = *it;
    double c = m[2].matched ? std::stod(m[2].str()) : (m[3].matched ? 1.0 : 0.0);
    if (m[1].str() == "-") c = -c;
    int e = m[4].matched ? std::stoi(m[4].str()) : (m[3].matched ? 1 : 0);
    M[e] += c;
  }
  return M;
}

Notes and testing

  • After collecting and combining terms, compute derivatives by iterating the map; remove zero coefficients and sort exponents descending when rendering.
  • Watch for input edge cases: implicit x, missing ^, whitespace, uppercase variables, and malformed tokens — add validation and unit tests.
  • Use fixed precision for floating coefficients when presenting results.

Recommended Answers

All 3 Replies

You would need to search for chars in strings, extract substrings from strings, convert numbers to strings and strings to numbers.

In general, most programming problems are easy to tackle if we reduce complexity by breaking up the problem into a number of smaller problems, each of which are easy to solve.

What we need to do is something like this:
given a string representation of a ploynomial: f(x) = "2.4x^4 - 1.2x^3 + 6x^2 + 4.1x + 9.2" We need to get the string representation of its derivative: f'(x) = "9.6x^3 - 3.6x^2 + 12x + 4.1" 1. Device a facility to represent a polynomial in our program.

A term of the polynomial can be represented as a pair with a double coefficient and an int exponent. typedef std::pair<double,int> term ; See:
For example, the second term of f(x) is given by std::make_pair( -1.2, 3 ) A polynomial can be represented as a sequence of terms typedef std::vector<term> polynomial ; See:
For example, the sequence for f(x) would have the following terms: (2.4,4), (-1.2,3), (6.0,2), (4.1,1), (9.0,0)

2. Write a function to get the derivative of a term term derivative( const term& t ) ; This is easy, derivative of (a,b) is (a*b,b-1); for example, derivative of (-1.2,3) would be (-3.6,2)

3. Write a function to get the derivative of a polynomial polynomial derivative( const polynomial& p ) ; This too is easy; return a sequence which contains the derivative of every term in p. (You can omit any term which has a coefficient of zero).

4. Write a function which gives the string representation of a term std::string to_string( const term& t ) ; use a std::ostringstream to do this. http://notfaq.wordpress.com/2006/08/30/c-convert-int-to-string/

If the term is (-1.2,3), return "-1.2x^3", if the term is (1.2,3) return "+1.2x^3", if the term has a coefficient of zero, return an empty string.

5. write a function which gives the string representation of a polynomial std::string to_string( const term& t ) ; Just concatenate the string representation of each term in the polynomial. If the leading sign in the result string is a '-', you may drop it.

6.Write a function to convert a string to a term. term to_term( const std::string& str ) ; use a std::istringstream for this.

term to_term( const std::string& str )
{
    // removing spaces from the string first makes it easier
    std::string cpy = str ;
    std::string::size_type pos = 0 ;
    while( ( pos = cpy.find( ' ', pos ) ) != std::string::npos ) cpy.erase(pos,1) ;

    double coefficient ;
    char variable ;
    char exp_symbol ;
    int exponent ;
    std::istringstream stm(cpy) ;
    stm >> coefficient >> variable >> exp_symbol >> exponent ;
          
    return std::make_pair( coefficient, exponent ) ;
}

7. write a function to convert a string to a polynomial. polynomial to_polynomial( const std::string& poly_str ) ; Parse poly_str to pick out the substring for each term in the polynomial.

Use std::string::find_first_of() http://www.cppreference.com/wiki/string/basic_string/find_first_of
and std::string::substr() http://www.cppreference.com/wiki/string/basic_string/substr
to do this.

Convert each substring to a term and return the sequence of terms.

8. Finally, put all these together to get the symbolic derivative of a polynomial string.

std::string symbolic_derivative( const std::string& str ) ;
   { return to_string( derivative( to_polynomial(str) ) ) ; }
commented: Nice one. +16

String class contains many public methods can be used to manipulate strings. Most useful, they often be resolved here.There are two types of string manipulation methods

1. String instance method call through a String object.Equals (string).
2. String class method or static method is called through the String class, String.

Thanks to "vijayan121" help, i have a clearer idea now about my program,and i have done something like a plan of it, but i'm not very clear about the syntax of the program,i don't really now what to fix and how.

#include <iostream>
#include <sstream>
#include <utility>
using namespace std

 int main()
 { string b = "4x^3+2x^5+3x^5";
   parse(b)
  term1= to_term(sub1);
  term2= to_term(sub2);
   term3= to_term(sub3);
   derivative(term1);
   derivative(term2);
   derivative(term3);
  cout<< to_string(derivative(term1))<<endl;
   cout<<to_string(derivative(term2))<<endl;
  cout<< to_string(derivative(term3))<<endl;
   
   return 0;
 }
   void parse (const string &a)

{  string sub1 = a.substr(0,4);
   cout<<sub1<<endl;

    string sub2 = a.substr(4, 5);
	cout<<sub2<<endl;

    string sub3 = a.substr(9, 5);
	<<cout<<sub3<<endl;

	
}


    
      int to_term( const string& str )
   
      {
   
      string cpy = str ;
   
      string::size_type pos = 0 ;
   
      while( ( pos = cpy.find( ' ', pos ) ) != string::npos ) cpy.erase(pos,1) ;
   
         
      double coefficient ;
   
      char variable ;
  
      char exp_symbol ;
  
      int exponent ;
  
      std::istringstream stm(cpy) ;
  
      stm >> coefficient >> variable >> exp_symbol >> exponent ;
  
       
  
      return std::make_pair( coefficient, exponent ) ;
  
      }
      
	 int derivative (const term& t)
       
	 {  return (coefficient*exponent,exponent-1);


	 }

	
	 char to_string(const term& t)
	 {  int c=coefficient;
	    string sc;
		std::stringstream out;
		out<<c;
		sc=out.str();

		int e=exponent;
		string se;
		std::stringstream out;
		out<<e;
		se=out.str();
        char stringterm= sc+"x^"+se;

		return stringterm;
	 }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.