4
$\begingroup$

StringQ returns True both for unformatted and internally formatted strings. To get True only for unformatted ones I have thought up the following function stringQ.

Please, can you point out pitfalls, if any ? Thanks!

stringQ[str_] := Module[{ret, subStr},
    subStr = "\!\(\*\nStyleBox[\"";
    ret = Quiet[
            If[
            StringQ[str] && StringFreeQ[str, subStr]
            ,True, False, False
            ]
        ];
    Return[ret];
];
$\endgroup$
5
  • $\begingroup$ what is "internally formatted string"? A string is a string. Why would it matter what is inside it? I did not know that Mathematica had 2 kinds of strings before. $\endgroup$
    – Nasser
    Commented Mar 25, 2014 at 1:04
  • $\begingroup$ @Nasser: Terminology straight from the documentation... $\endgroup$
    – ciao
    Commented Mar 25, 2014 at 1:10
  • $\begingroup$ @rasher, ok, I just never heard or seen something called "internally formatted string" reading Mathematica documentation. I just googled this and it turned no hit. But may be I just need to look harder. $\endgroup$
    – Nasser
    Commented Mar 25, 2014 at 1:16
  • $\begingroup$ @Nasser: See scope under StringQ documentation. $\endgroup$
    – ciao
    Commented Mar 25, 2014 at 1:28
  • $\begingroup$ @rasher thanks, I see it now. But for me it is just a string. Anything with a starting " and ending " is a string. But I understand now the OP wanted to parse/detect it to see if it it contains Mathematica specific content. Ok. $\endgroup$
    – Nasser
    Commented Mar 25, 2014 at 1:34

1 Answer 1

4
$\begingroup$

You method seems fine. Here are some alternatives:

stringFQ[string_String] := Module[{str, res},
   res = Read[str = StringToStream[string], String];
   Close[str];
   res == string];

stringFQ2[string_String] := StringFormat[string] != "Binary"

stringFQ3[string_String] := ExportString[string, "Text"] === string

stringFQ4[string_String] := string == ToString[string]

For huge strings, the first can be 10+X faster on those containing format constructs.

The second is about as concise as it can get I suppose, see docs for heuristics caveats.

Third is nearly as compact, no caveats other than slower than others on huge strings.

Fourth is also compact, about same speed as others for large strings.

So, many ways to skin this cat, depends on your needs for speed...

$\endgroup$

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.