1
$\begingroup$

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.

$\endgroup$
  • $\begingroup$ Would x^2 + 11 be length 4 or 5? Or Integrate[x, {x,0,-1}]? $\endgroup$ – WeavingBird1917 Apr 18 at 16:47
  • $\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 at 16:50
  • 3
    $\begingroup$ It neither simple, nor well defined question. The closest I can think of is LeafCount. $\endgroup$ – m0nhawk Apr 18 at 17:45
  • $\begingroup$ I think LeafCount looks like a very good method for my purpose. $\endgroup$ – user120911 Apr 18 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$ – Alexei Boulbitch Apr 18 at 21:16
0
$\begingroup$
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 *)
| improve this answer | |
$\endgroup$
  • 1
    $\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$ – J. M.'s technical difficulties Apr 19 at 6:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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