[Gambas-user] Boxed string question

Tobias Boege taboege at gmail.com
Wed Sep 11 14:43:19 CEST 2019


On Wed, 11 Sep 2019, Gianluigi wrote:
> What do you think about these solutions (obviously the second solution is
> not mine :-P)?
> 
> Private Function ProperCase(value As String) As String
> 
>   Dim ss As String[] = Split(value, " ")
> 
>   value = ""
>   For Each s As String In ss
>     value &= String.UCaseFirst(s) & " "
>   Next
>   Return RTrim(value)
> 
> End
> 
> Private Function ProperCase(value As String) As String
> 
>   Dim bb As Byte[]
> 
>   bb = Byte[].FromString(value)
>   For i As Integer = 0 To bb.Max - 1
>     If bb[i + 1] \ bb[i] = 3 Then bb[i + 1] = bb[i + 1] - 32
>   Next
>   Return bb.ToString(0, bb.Count)
> 
> End
> 

I would go with the first one. Whoever wrote the second one has to
pay a little more attention to detail:

  - it has disastrous effects on UTF-8 strings, like turning "Aß" into
    "A" followed by garbage. Go do the math why that is :-)
  - it does nothing on "ä ö ü ß" for the same reason,
  - it converts " ~" to " ^" for the same reason,
  - heck it even turns " !c" into " !C" but leaves " !b" unchanged
    for the same reason,
  - it does not uppercase the first character in the string for an
    unrelated reason.

Unicode is really, really hard [1]. If you want to support it (which
I've been just assuming throughout this thread because you started off
using methods of the String class), then you should use methods that
promise to do it for you for everything and never ever work with Bytes,
even if it means you have to split a string into an array and put it
back together again.

Regards,
Tobi

[1] Just a very recent example: https://hsivonen.fi/string-length/

-- 
"There's an old saying: Don't change anything... ever!" -- Mr. Monk


More information about the User mailing list