Tag Info

Hot answers tagged

33

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, ...


15

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}] ...


14

str = "[can {and it(it (mix) up)} look silly]"; i = 10; StringJoin @@ Last[Replace[Characters@str, {"[" | "(" | "{" :> Sow[" ", --i], "]" | ")" | "}" :> Sow["", ++i], c_ :> Sow[c, i]} , 1] ~Reap~ Range@10] (* " mix it up and it can look silly" *) This just scans through the characters one at a time and Sows them with an integer tag. ...


10

This is a straightforward attempt at a recursive descent parser, favoring readability over brevity. First, the tokenizer: tokenize[str_] := DeleteCases[StringCases[str, { "(" -> open[1], "[" -> open[2], "{" -> open[3], ")" -> close[1], "]" -> close[2], "}" -> close[3], x : (Except[Characters["()[]{}"]] ..) ...


9

As no one gave a FixedPoint answer, here is one: preparedStr = StringReplace[ "((your[drink {remember to}]) ovaltine)", { RegularExpression["[{[(]"] -> "{", RegularExpression["[)\]}]"] -> "}" }] "{{your{drink {remember to}}} ovaltine}" lst = {}; ...


8

Reset the kernel first. str = "[can {and it(it (mix) up)} look silly]" new = StringReplace[ StringReplace[str, {"(" | "[" -> "{", ")" | "]" -> "}"}], {(a : WordCharacter ~~ " " | "" ~~ "{") :> a <> ",{", (a : WordCharacter ~~ " " ~~ b : WordCharacter) :> a <> "," <> b, ("}" ~~ " " | "" ~~ b : ...


6

str = "[to {quite similar(answer (My) is)} Kuba's answer]"; mid = StringReplace[ StringReplace[ "Hold@" <> str, {"[" | "(" -> "{", "]" | ")" -> "}"}] // ToExpression // InputForm // ToString, "*" -> ","] // ToExpression // ReleaseHold {to, {quite, similar, {answer, {My}, is}}, Derivative[1][Kuba], s, answer} ...


5

This will give you an idea to start with I think: target = "[racket for {brackets (matching) is a} computers]" Rest@Reap[ Nest[With[{s = StringPosition[#, {"{", "(", "["}][[-1, 1]], e = StringPosition[#, {"}", ")", "]"}][[1, 1]]}, Sow[StringTake[#, {s + 1, e - 1}]]; StringDrop[#, {s, e}]] &, target, Length@StringPosition[target, ...


5

new one This seems to be quite fast (didn't test with yours) sc[{n_String}] := n; sc[s_] := StringJoin[StringDrop[Most[s], -1]] <> Last[s] sc /@ Split[testLines, StringMatchQ[#, "*\\"] &] old one StringJoin @@@ ( Split[testLines, StringMatchQ[#, "*\\"] &] /. s : {Repeated[_String, {2, ∞}]} :> ...


4

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 == ...


4

This solution requires that you know some character that does not occur in your string, in this example "|" jacob[strList_] := StringSplit[ StringReplace[StringJoin[Riffle[strList, "|"]], "\\|" -> ""], "|"] Maybe it will be fast because there are few function calls. Modified definitions of other answers sc[{n_String}] := n; sc[s_] := ...


4

That's because "Base64" is not a format but an encoding and you still need to tell Mathematica what format to import after decoding from Base64. This is described in the documentation. Try this: ImportString[s, {"Base64", "String"}]


4

Please reference: How do I perform string matching and replacements? Using StringExpression: string = ExampleData[{"Text", "DeclarationOfIndependence"}]; StringCases[string, _ ~~ _ ~~ _ ~~ "q" ~~ _ ~~ _ ~~ _] {"d equal", " requir", "d equal", "linquis", "or quar", " acquie"} Or: StringCases[string, # ~~ "q" ~~ #] & @ Repeated[_, {3}] {"d ...


4

str = "[can {and it(it (mix) up)} look silly]" paren = {{"\\(", "\\)"}, {"\\[", "\\]"}, {"{", "}"}}; allparen = StringJoin@Flatten[paren]; re = RegularExpression[ StringTake[ StringJoin[#[[1]] <> "[^" <> allparen <> "]*" <> #[[2]] <> "|" & /@paren] , {1, -2}]]; sr := Function[strl, Fold[ (Sow[" " ...


4

The code below will identify "hits" using the requested rules. It works by computing the intersection of two sets of positions: 1) the positions of "string2" and 2) the allowable positions determined by leading and trailing "windows" relative to each occurrence of "string1". The count function will return the number of hits and position give the positions ...


3

This might be somewhat inefficient, but seems to work: ClearAll[count]; count[ big_String, fstr_String, secstr_String, lb_Integer?Positive, ub_Integer?Positive ]:= Module[{pos,pairQ}, pairQ= Function[ {fst,sec}, Boole[ ...


3

This measures frame rate using simple Manipulate that does very little computation other than calculating FPS and then display an image. It finds fps as number of refreshes made so far divided by number of seconds elapsed. I did not use a moving average here, just kept a record of the number of times Manipulate is called and the time since start. This ...


3

The epoch starts from jan 01 1970, so you can do: to = AbsoluteTime[{1970, 1, 1, 0, 0, 0.`}]; DateString[1395858190 + to] Wed 26 Mar 2014 18:23:10 From http://www.epochconverter.com/ GMT: Wed, 26 Mar 2014 18:23:10 GMT


3

Possibly this is sufficient: in = "174,861.00 ( 4,053.52) 206,850.48 118.29 ( 31,989.48)"; StringReplace[in, {"," -> "", "(" ~~ Whitespace -> "(", Whitespace -> ","}] "174861.00,(4053.52),206850.48,118.29,(31989.48)"


3

But if you always want to replace the sequence brace, spaces, digit, why don't you just say so? str="174,861.00 ( 4,053.52) 206,850.48 118.29 ( 31,989.48)"; StringReplace[ StringReplace[str, d1 : DigitCharacter ~~ "," ~~ d2 : DigitCharacter :> d1 ~~ d2], {"(" ~~ Whitespace .. ~~ i : DigitCharacter -> "(" ~~ i, Longest[Whitespace ...


3

This is similar to Kuba's solution, but uses the listability of ToCharacterCode/FromCharacterCode instead of string patterns. Sometimes, this can be a bit faster than string manipulations: joinWords[list_] := Join @@@ (Split[ToCharacterCode@list, Last[#] == 92 &] /. {h__, 92} :> {h}) // FromCharacterCode joinWords@Pillsy`testLines (* ...


2

The contents of your file probably look like this: str = " 3,-3,0,5,5,0.000208 -3,-3,0,5,5,0.000208 3,-3,0,5,5,0.000208" In the following I am going to use ImportString to be able to work with str, but the same applies to Import as well. The values are separated by commas. This format is called a CSV format---Comma Separated Values. Make sure you ...


2

Just some other functions to consider: IntegerDigits an take a base argument, e.g. IntegerDigits[5,2] yields {1,0,1} FromDigits is the inverse: FromDigits[{1,0,1},2] yields 5 If the issue is for display purpose and not specifically need for strings then BaseForm will display binary numbers with subscript of 2, i.e.BaseForm[5,2] yields: $101_2$ so for ...


2

Using the code for mark, from linked question: f[string_, cases_] := Module[{pos, agg, res}, pos = StringPosition[string, cases]; agg = {Switch[#[[ 1, 2]], 1, Blue, 2, Brown, _, Red], #[[ ;; , {1}]] } & /@ GatherBy[Tally@Flatten[Range @@@ pos], Last]; mark[string, agg] ] f["TheBrownFox", {"TheBrown", "BrownFox"}] ...


2

testString = "100 aa bbc%j%b%wa ajjcj11j0%2wj fc"; StringJoin@StringCases[testString, {"a", "j", "c", " "}] (* aa cja ajjcjjj c *) The second argument for StringCases can use character ranges, etc. As to "bulk" but specific upcase/downcase, something like: StringReplace[%, (# -> ToUpperCase[#]) & /@ {"c", "j"}] (* aa CJa aJJCJJJ C *)


2

Let's make some data first str1 = Import["http://nl.wikipedia.org/wiki/Kat_(dier)", "Plaintext"]; str2 = Import["http://nl.wikipedia.org/wiki/Hond", "Plaintext"]; This is a shorter way to get the words words1 = StringCases[str, WordCharacter ..]; words2 = StringCases[str2, WordCharacter ..]; We could now immediately delete the "stopwoorden" ...


1

Updated: vList = Map[StringJoin, Tuples[{"0", "1", "2"}, 4]]; testF = EditDistance[#[[1]], #[[2]]] > 3 && StringReverse[#[[1]]] == #[[2]] &; e1 = vList[[#]] & /@ (SparseArray[{{i_, j_} /; (i>j&&testF[{vList[[i]], vList[[j]]}]) -> 1}, Length@vList {1, 1}]["NonzeroPositions"]); (* or *) e2 = Select[Subsets[vList, {2}], ...


1

Personally, I would use common regural expression syntax, since this can be checked also by non-Mathematica programmers: str = "174,861.00 ( 4,053.52) 206,850.48 118.29 ( 31,989.48)"; StringReplace[str, { "," -> "", RegularExpression[" \\( +"] -> ",(", RegularExpression["\\) +"] -> ")," , RegularExpression[" +"] ...


1

input = StringSplit[#, "\n"] & /@ StringSplit[Import["c:\\Users\\Rasher\\Documents\\testtext.txt"], "^"] title = input[[All, 1]] text = input[[All, 2 ;;]] Titles in titles, obviously, with indicator stripped. Text in corresponding text element, as a list with each line of text an element.


1

One alternative solution, that seems faster, but isn't really that much less horrible, uses Sow/Reap and increments a counter to use as a tag: Pillsy`reapCatenateContinuedLines[lines : {___String}] := Module[{counter = 0}, StringJoin @@@ Last@Reap[ Scan[ If[StringMatchQ[#, ___ ~~ "\\"], Sow[StringDrop[#, -1], counter], Sow[#, ...



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