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.

  • $\begingroup$ 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. $\endgroup$
    – user120911
    Apr 18, 2020 at 16:50
  • 3
    $\begingroup$ It neither simple, nor well defined question. The closest I can think of is LeafCount. $\endgroup$
    – m0nhawk
    Apr 18, 2020 at 17:45
  • $\begingroup$ I think LeafCount looks like a very good method for my purpose. $\endgroup$
    – user120911
    Apr 18, 2020 at 18:20
  • $\begingroup$ 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. $\endgroup$ Apr 18, 2020 at 21:16

1 Answer 1

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

seems to do what you're looking for.

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

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

(* 3 *)
  • 2
    $\begingroup$ 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]] $\endgroup$ Apr 19, 2020 at 6:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.