# Optimizing an equation - show the length of an equation, including operators

A simple, but I think useful question to know the answer for.

How can I quickly count the length in my equation, including +,-, and so on?

For example, $$x^2+1$$ has a length of 4.

• Would x^2 + 11 be length 4 or 5? Or Integrate[x, {x,0,-1}]? – WeavingBird1917 Apr 18 at 16:47
• The first would be 5 (any spaces are ignored). The second, output at 1/2 would be 3. But I see more thought needs to go into this. – user120911 Apr 18 at 16:50
• It neither simple, nor well defined question. The closest I can think of is LeafCount. – m0nhawk Apr 18 at 17:45
• I think LeafCount looks like a very good method for my purpose. – user120911 Apr 18 at 18:20
• In Mma the length of an expression is a well-defimed thing. Length[x^2 + 11] yields 2, rather than 5. I conclude that under the term "length" the OP understands something different from what one expects in Mma. Therefore, the question in its present form is misleading. I would recommend to reformulate the question and bring it in agreement with the Wolfram language. Otherwise, I think in its present form the question should be closed. – Alexei Boulbitch Apr 18 at 21:16

f = StringLength@*StringDelete[WhitespaceCharacter]@*ToString


seems to do what you're looking for.

f[x^2 + 1]
(* 4 *)

f[x^2 + 11]
(* 5 *)

f[1/2]
(* 3 *)

• Of note is that ToString[] accepts a second argument controlling the kind of string returned, e.g. StringLength[ToString[x^2 + 1, InputForm]] vs. StringLength[ToString[x^2 + 1, StandardForm]] – J. M.'s technical difficulties Apr 19 at 6:35