0
$\begingroup$

Considering we have few strings:

s1 = "dasbdk        "
s2 = "asdnkal asn knkl nkn dvklsn     "
s3 = "    jbjkbasd nklnkln     "

Q1:

How can the blank-spaces in the end only be trimmed out to have the following result:

s1 = "dasbdk"
s2 = "asdnkal asn knkl nkn dvklsn"
s3 = "    jbjkbasd nklnkln"

Q2

How can any 2-or-more sequence of blank-spaces be trimmed out to have the following result:

s1 = "dasbdk"
s2 = "asdnkal asn knkl nkn dvklsn"
s3 = "jbjkbasd nklnkln"

Thanks!

$\endgroup$
4
  • $\begingroup$ Have you seen StringTrim[]? $\endgroup$ Jun 24, 2015 at 8:19
  • $\begingroup$ StringTrim[] does only Q2, right? $\endgroup$
    – SuTron
    Jun 24, 2015 at 8:39
  • 1
    $\begingroup$ @SuTron StringTrim can take a second argument to target any pattern, and so can do Q1 and Q2. $\endgroup$
    – SquareOne
    Jun 24, 2015 at 9:34
  • $\begingroup$ The most natural way seems to be simply: StringReplace[string, " " -> ""] $\endgroup$ Jun 24, 2015 at 9:56

4 Answers 4

4
$\begingroup$

As commented, StringTrim for example will do the job.

For example :

StringTrim[s3]
StringTrim[s3, StartOfString ~~ WhitespaceCharacter ..]
StringTrim[s3, WhitespaceCharacter .. ~~ EndOfString]

return

"jbjkbasd nklnkln"
"jbjkbasd nklnkln     "
"    jbjkbasd nklnkln"
$\endgroup$
1
$\begingroup$

Q1

Column[StringReplace[#, " " .. ~~ EndOfString -> ""] & /@ {s1, s2, s3}]
dasbdk
asdnkal asn knkl nkn dvklsn
    jbjkbasd nklnkln

Q2

Column[StringTrim[#] & /@ {s1, s2, s3}]
dasbdk
asdnkal asn knkl nkn dvklsn
jbjkbasd nklnkln
$\endgroup$
1
$\begingroup$

As already noted for Q2 the best solution is of course StringTrim. For Q1 here is an alternative using regular expressions:

stringTrimAtEnd = StringReplace[#,RegularExpression["\\s*$"] :> ""] &
$\endgroup$
0
$\begingroup$

Q1: keep deleting blank spaces from the end until they're gone (not very elegant but it works):

s3 = "    jbjkbasd nklnkln     "    
While[Characters[s3][[-1]] == " ", 
     s3 = StringJoin@Delete[Characters[s3], -1]]`

Q2: if you use StringReplace[] you can also delete multiple blank spaces in the middle of the String:

StringReplace["   asd   nkal asn  knkl nkn dvklsn     ", 
 " " ~~ " " .. -> ""]
$\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.