Quantcast
Channel: Active questions tagged string-manipulation - Mathematica Stack Exchange
Viewing all articles
Browse latest Browse all 186

How to convert strings to the same pattern

$
0
0

I have some sets of random strings. These strings may have one of the special characters (+,-,=) as a prefix or suffix, or both. Different special characters cannot be mixed in the same set.I want to convert the strings in a set into the same pattern depending on how the special characters are attached. For example, if a set of strings contains some strings with a special character as a prefix and some as a suffix, all strings in the set must have the special character at both the beginning and the end.  Also, if all strings do not have any special character, the set does not change.My attempt is as follows:

convert[n_, x_] := Block[{temp = x},       If[Select[temp, StringMatchQ[#, n ~~ __] &] != {},temp = n <> # & /@ temp];      If[Select[temp, StringMatchQ[#, __ ~~ n] &] != {},temp = # <> n & /@ temp];      StringReplace[#, n <> n :> n] & /@ temp]sampledata = {{"-Qrs2","tu44-"},{"abC23+","dE45f","+gh+"},  {"=ijk56","=LkM23","nop"},{"vw77","xyz"}}convert["=", convert["-", convert["+", #]]] & /@ sampledata

gives results as desired:

{{"-Qrs2-","-tu44-"},{"+abC23+","+dE45f+","+gh+"}, {"=ijk56","=LkM23","=nop"},{"vw77","xyz"}}

But I think there must be a more efficient way.


Viewing all articles
Browse latest Browse all 186

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>