Message Boards Message Boards

0
|
2539 Views
|
2 Replies
|
0 Total Likes
View groups...
Share
Share this post:

Create a function that removes symbols

Posted 10 years ago

I am trying to write a function in Mathematica that takes a string and removes any spaces and punctuations and also turns capital letters into their lowercase equivalents, and keeps all lower case letters. This is what I have so far, and it doesn't seem to work.

formatText[plaintext_] := Module[{c = ToCharacterCode[plaintext], x = 0, z = {}}, 
  While[x < StringLength[plaintext], If [c[[x]] <= 64 || 91 <= c[[x]] <= 96 || c[[x]] >= 123, 
  c[[x]] = 0, //here I just need it to do nothing
   If[65 <= c[[x]] <= 90, Append[z, c[[x]] + 32], 
  Append[z, c[[x]]]]]; x = x++;]; FromCharacterCode[z]];

Any help is appreciated.

POSTED BY: A J
2 Replies
Posted 10 years ago

That is a lot simpler than what I had tried. Thank you!

POSTED BY: A J

Mathematica has some very powerful string manipulation commands. Try the following:

In[1]:= modifyString[str_String] := 
 ToLowerCase[StringReplace[str, Except[LetterCharacter] -> ""]]

In[2]:= modifyString["I am trying to write a function in Mathematica \
that takes a string and removes any spaces and punctuations and also \
turns capital letters into their lowercase equivalents, and keeps all \
lower case letters. 

 This is what I have so far, and it doesn't seem to work."]

Out[2]= "iamtryingtowriteafunctioninmathematicathattakesastringandremo\
vesanyspacesandpunctuationsandalsoturnscapitallettersintotheirlowercas\
eequivalentsandkeepsalllowercaselettersthisiswhatihavesofaranditdoesnt\
seemtowork"

If you want to allow digits as well then change LetterCharacter above to WordCharacter.

Note that in the above input and output the backslash characters are just a result of the copy and past from Mathematica into this forum. They are not part of the input or the output.

POSTED BY: David Reiss
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract