# Tag Info

84

In this response, I will focus upon the programming paradigm change when moving from Java to Mathematica. I will emphasize two differences between the languages. The first concerns the "feel" of writing Mathematica code. The second is about how iteration is expressed. The "Feel" of Mathematica Java is a reasonably conventional programming language, ...

76

I think probably the cleanest way to do this (at least, if you have only a single string, or are faced with a separate string for each number you wish to convert as a result of some other process) is to use the undocumented function InternalStringToDouble, i.e.: s = "1.23e-5"; InternalStringToDouble[s] which gives: 0.0000123 However, if you are trying ...

48

Preamble and motivation While I am much late to the party here, I hope this answer will not be totally useless. This is a first in a series of posts where I will advocate a wider use of Java in our workflow, and present/describe certain toolset to reduce the mental overhead of this. So, my motivation here is not to provide a faster or more elegant solution, ...

42

The undocumented SystemDumpshowStringDiff function neatly does the diff and highlights it for you. The simplest usage is: SystemDumpshowStringDiff[text1, text2] You can choose custom colours for the highlights with the Styles option. You can also change the background, font weight, add a strikethrough, etc.: SystemDumpshowStringDiff[text1, text2, ...

39

Use Row to join them: Omega = "text"; joined = Row[{Style[Omega, Lighter[Blue, .1]], Style[Omega, Darker[LightBlue, .1]]}]; Print[joined]

37

Given two styled items: omega = "text" items = { Style[omega,Lighter[Blue,.1]], Style[omega,Darker[LightBlue,.1]] } We can produce a single string with both stylings if we convert each item into a StandardForm string prior to joining them: Apply[StringJoin, ToString[#, StandardForm] & /@ items] The following screenshot shows the results:

30

StringReplace method After reading other answers I was inspired to write a new method. I place it first because it is almost as concise as the method below yet it is more robust (and safe) because it preserves strings as strings. str = "[can {and it(it (mix) up)} look silly]"; StringReplace[str, {"["|"{"|"(" -> -1, "]"|"}"|")" -> 1, " " -> 0}] //...

29

There are three different mechanisms provided for matching string patterns in Mathematica. Each of these must be used within functions that are equipped to handle strings. You cannot, for instance, use: {"abc", "def", "ghi"} /. "a*" -> 1 Replace["downwind", "downw" -> "resc"] to any effect. Instead you would use: {"abc", "def", "ghi"} /. ...

28

Mathematica supports two related functions, LongestCommonSequence[] and LongestCommonSubsequence[]. The first one finds the longest (contiguous or non-contiguous) sequence common to the two strings given as arguments to it: LongestCommonSequence["AAABBBBCCCCC", "CCCBBBAAABABA"] "AAABB" while the second function is constrained to give the longest contiguous ...

25

I've had a need for such a function several times, and I found this implementation of C-style *printf functions, by Vlad Seghete. To use it, all you need to do is extract the files to \$UserBaseDirectory/MathPrintF/ and you're all set. Here's an example once you've installed it: <<MathPrintF sprintf["%d %s %d %s, %s %s %s %s", Sequence @@ Riffle[...

25

Here is a hybrid recursive/StringReplaceList method. It builds a tree representing all possible splits. Now with a massive speed improvement thanks to Rojo's brilliance. Updated element list per bobthechemist. elements = Array[ElementData[#, "Symbol"] &, 118] /. {"Uup" -> "Mc", "Uus" -> "Ts", "Uuo" -> "Og"} // ToLowerCase; f1[""] =...

25

My guess is that WRI made an explicit design decision to separate general patterns and string patterns in order to manage ambiguities where the two syntaxes overlap. As a simple example, consider the pattern (_~~"x")... When we draw no distinction between general patterns and string patterns, then this expression is ambiguous. If interpreted as a general ...

25

Using StringPatternPatternConvert we can find the regexp into which Mathematica converts the original string expression: StringPatternPatternConvert[Except["b"] .. ~~ "b"][[1]] "(?ms)(?:[^b])+b" The only difference as compared to the direct semantic translation is that the negated character class [^b] is enclosed by redundant non-capturing group (?: … )....

24

Try this: StringCases["ABCDEFGHIJK", LetterCharacter ~~ LetterCharacter] {"AB", "CD", "EF", "GH", "IJ"} or for more general cases (i.e. not just for letters, but any characters, and for any partition size): stringPartition1[s_String, n_Integer] := StringCases[s, StringExpression @@ Table[_, {n}]]; It is more elegant though to use Repeated (thanks ...

24

For most strings you can use simply: ToString[string] Or more rigorously: ToString[string, OutputForm] Observe: If your styled string includes two dimensional formatting that you do not wish to change you will find OutputForm unacceptable. Of course the 2D formatting itself will mean that the string cannot be in a "plain" form, but we can still strip ...

24

From the documentation, though IMHO not easy to find: StringReplace["this is a test", WordBoundary ~~ x_ :> ToUpperCase[x]] "This Is A Test" István Zachar highlighted a problem with WordBoundary that I'm still trying to understand. Nevertheless it seems that one can use: strAcc = "árv ízt űr őt ük örf úr óg ép"; StringReplace[strAcc, z : (...

23

Not as such. The closest equivalent is StringForm, but it doesn't provide the formatting options that the printf family does. StringForm gets a lot of use in the creation of messages. Example: StringForm["The value of Pi is ", NumberForm[N[Pi], 3]] (* ==> "The value of Pi is 3.14" *) Note that StringForm does not create a string, it merely displays ...

23

I suggest an approach based on creating lexical and / or dynamic environments (custom scoping constructs if you wish), inside which the rules of our "universe" will be altered. I will illustrate with a dynamic environment: ClearAll[withStringManipulations]; SetAttributes[withStringManipulations, HoldAll]; withStringManipulations[code_] := Internal`...

23

Ok, since you dismissed SplitBy, which IMO is quite clean, and you wanted other's ideas, here's an unconventional solution that relies on a side-effect of how StringJoin works :) list = {"a", "b", 1, 2, 3, 4, "a", 2, 2, 2, "edg", "?"}; List @@ Quiet@StringJoin@list (* {"ab", 1, 2, 3, 4, "a", 2, 2, 2, "edg?"} *) I wouldn't recommend this for production code....

23

This is a bug in version 10.1.0. We decided it was serious enough to warrant a fix via an automatic paclet update. The paclet has been pushed live and Mathematica should install it automatically once it does a periodic check with the paclet server. It should take about a week or so. To install it right away, you can do PacletInstall["StringPatternFix"]. You ...

23

Here we go... highlightString[board_, str_] := With[{l = Characters[str]}, board // horizontal[l] // vertical[l] // diagonal[l] // diagonalReversed[l]] horizontal[letters_][board_] := applyStyle[letters] /@ board vertical[letters_][board_] := Transpose[applyStyle[letters] /@ Transpose[board]] diagonal[letters_][board_] := diagonalD[applyStyle[letters] /@ ...

22

A very simple and straightforward test for square-freeness (and should be reasonably fast) is: squareFreeQ[str_] := StringFreeQ[str, x__ ~~ x__] Testing on your inputs: squareFreeQ["0101"] (* False*) squareFreeQ["0102012021"] (* True *) You can then possibly restrict this further to operate only on certain alphabets using Repeated and Alternatives. ...

21

s = "1.23e-5" # &[Read[#, Number], Close@#]&[ StringToStream@s ] Which is not as good as what you started with. Note that it is important to close the stream. Szabolcs says this is difficult to read. That was surely not my intention. You could also write it verbosely like this: fromC = Module[{output, stream}, stream = StringToStream[...

21

Here's a start (perhaps it's better to say continuation since you've already gotten started): Row@Flatten[sa /. {a_, b_} :> { Style[a, Red], "(", Style[b, Green], ")"}] By capturing the word fragmentth to the left and right of a, you thhould be able to end up with thomething more like:

21

Preamble What happens can be understood when we recall that Rule is a scoping construct. The general issues related to variable renamings in scoping constructs have been considered in more details in this answer. General Now, to this particular case. When the code runs, the external RuleDelayed considers the situation "dangerous" and performs variable ...

21

str = {"1,2,3,5,10,12,13,17,26,30,32,41,42,43,113,115,121,125"} Flatten@ToExpression@StringSplit[str, ","] Short explanation: After executing StringSplit you get a list of separated "StringNumbers" like {{"1", "2", ... "125"}} ToExpression converts these "StringNumbers" to Integers. Flatten removes the outermost brackets. You can even omit Flatten by ...

20

Here is the regular-expression way: chunk[s_, n_] := StringCases[s, RegularExpression[".{1," <> ToString[n] <> "}"]] chunk["Hello this is a test string", 2] {"He", "ll", "o ", "th", "is", " i", "s ", "a ", "te", "st", " s", "tr", "in", "g"} chunk["Hello this is a test string", 4] {"Hell", "o th", "is i", "s a ", "test", " str", "ing"} ...

20

Also, using pattern matching,just in case: {{a, b, c, d, e, f, g}, {x, a, r, b, c, j}} /. {{___, Longest[y__], ___}, {___, y__, ___}} -> {y} (* -> {b, c} *) Edit With this approach you can do one thing that seems not trivial by using the faster LongestCommonSequence[] function: finding the maximal common subsequence among several lists: {{1, 2, 3, ...

20

To remove accents from a string I use this function: removeAccent[string_] := Module[{accentMap,l1,l2}, l1 = Characters["ŠŽšžŸÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðñòóôõöùúûüýÿ"]; l2 = Characters["SZszYAAAAAACEEEEIIIIDNOOOOOUUUUYaaaaaaceeeeiiiidnooooouuuuyy"]; accentMap = Thread[l1 -> l2]; StringReplace[string, accentMap] ] So, if ...

20

It might be overkill, but with: DictionaryLookup[{"German", All}] you get a list of every German word. To be a bit more precise, you could then narrow things with string searches, i.e. DictionaryLookup[{"German", "a" ~~ ___ ~~ "b"}] gets you a list of words that begin with a and end with b. Full documentation is here.

Only top voted, non community-wiki answers of a minimum length are eligible