简体   繁体   English

为什么此块不修剪字符串

[英]Why this block is not trimming string

I am trying following block to trim leading spaces from the sent string: 我正在尝试以下块来修剪发送的字符串中的前导空格:

trimleading := [ :str|
    ch := (str byteAt: 1).          "get first character: ERROR HERE"
    ret := str copyFrom: 1.         "make a copy of sent string"
    [ch = ' '] whileTrue: [         "while first char is space"
        ret := (ret copyFrom: 2).   "copy from 2nd char"
        ch := ret byteAt: 1.        "again test first char"
        ].
    ret                             "value is modified string"
].

('>>',(trimleading value: '    this is a test  '),'<<') displayNl.

It works without any error but does not remove leading spaces from the sent string. 它可以正常工作,但不会从发送的字符串中删除前导空格。 The return value is identical to sent string. 返回值与发送的字符串相同。

Apparently, first character ch is not being picked up. 显然,第一个字符ch没有被拾取。 at: is also not working instead of byteAt: . at:也不能代替byteAt:

Where is the problem and how can it be solved? 问题在哪里,如何解决? Thanks. 谢谢。

The problem is that you are comparing the first element as a byte, which is a not a Character but a number, to a string with one Space character. 问题在于您正在将第一个元素(不是字节,而是数字)作为一个字节与带有一个空格字符的字符串进行比较。 In Smalltalk integers, characters and strings are different, so you should compare against the corresponding type. 在Smalltalk整数中,字符和字符串是不同的,因此应与相应的类型进行比较。 In this case you can get the first character of the string with at: instead of byteAt: , or compare to the ascii value of space, which is 32, or Character space asciiValue or $ asciiValue . 在这种情况下,您可以使用at:而不是byteAt:来获取字符串的第一个字符,或者将其与space的ascii值(即32)或Character space asciiValue$ asciiValue Here is one possible solution: 这是一种可能的解决方案:

    trimleading := [ :str | 
    ch := str at: 1.
    ret := str copyFrom: 1 to: str size.
    [ ch = Character space ]
        whileTrue: [ ret := ret copyFrom: 2 to: ret size.
            ch := ret at: 1 ].
    ret ].
    ^ ('>>' , (trimleading value: '    this is a test  ') , '<<')
        displayNl

as you may have noticed, I changed copyFrom: to copyFrom:to: . 您可能已经注意到,我将copyFrom:更改为copyFrom:to: This is because, unlike what one would think, copyFrom: doesn't copy from the position passed to the end of the string, but tries to copy the receiver from another object (this behavior is inherited from Object ). 这是因为,不同于人们的想法, copyFrom:不会从传递到字符串末尾的位置进行复制,而是尝试从另一个对象复制接收者(此行为是从Object继承的)。

There are quite a few other possible improvements and simplifications to your code, I leave that to you as an exercise. 您的代码还有许多其他可能的改进和简化,我将其留给您作为练习。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM