String」タグアーカイブ

文字列に合わせたUI.Textのサイズを取得する方法

UnityのUI.Textで、実際にテキストを表示した際のサイズが知りたい場合はpreferredWidthpreferredHeightを使って調べることができるそうです。

使い方

Text text;

float width = text.preferredWidth;
float height = text.preferredHeight;

テキストのサイズに合わせてUIを調整したい場合に便利かなと思います。

TextMeshPro

TexhMeshProの場合もpreferredWidthpreferredHeightを使って実際のサイズを調べることができるようです。

使い方

TMPro.TextMeshProUGUI text;

float width = text.preferredWidth;
float height = text.preferredHeight;

リンク

Unity – Scripting API: ILayoutElement
https://docs.unity3d.com/ScriptReference/UI.ILayoutElement.html

Class TextMeshProUGUI | TextMeshPro | 1.5.6
https://docs.unity3d.com/Packages/com.unity.textmeshpro@1.5/api/TMPro.TextMeshProUGUI.html

C#の文字列補完

string.Format

string.Formatを使うと、次のような感じで変数の値を文字列に変換して出力できます。

コード

string name = "abc";
int value = 123;
Debug.Log(string.Format("name={0}, value={1}", name, value));

出力

name=abc, value=123

便利でよく使っていたのですが、C#6の文字列補完を使うとより簡潔な感じで書けるみたいです。

C#6の文字列補完

コード

string name = "abc";
int value = 123;
Debug.Log($"name={name}, value={value}");

出力

name=abc, value=123

16進表記

数値を16進表記で出力したい場合は:xを追加します。
:x4のようにして桁数を指定することもできます。

コード

int value = 123;
Debug.Log($"{value:x} {value:x4}");

出力

7b 007b

リンク

$ – string interpolation – C# reference | Microsoft Docs
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated

PythonのString Formattingを拡張

Python 3で追加されたformatを使うと文字列操作が便利になります。

使い方は次のような感じです。(参考:Pythonの新しい文字列書式操作

>>> '{0} + {1} = {2}'.format(1, 2, 1+2)
'1 + 2 = 3'

string.Formatterを継承すると、この文字列操作を拡張することができるそうです。

拡張の仕方は以下のような感じです。

class Formatter(string.Formatter):
  def format_field(self, value, spec):
    # 必要な処理
    return 'value'

サンプル

このstring.Formatterを継承してupperlowerを書式指定文字列に使うと大文字・小文字に変換するサンプルを作ってみました。

import string
class Formatter(string.Formatter):
  def format_field(self, value, spec):
    if spec == 'upper': value, spec = value.upper(), ''
    elif spec == 'lower': value, spec = value.lower(), ''
    return super(Formatter, self).format_field(value, spec)

使い方は以下のような感じです。

>>> f = Formatter()
>>> f.format('{name} {name:upper} {name:lower}', name='Alice')
'Alice ALICE alice'

template engine

このString Formattingを使ってtemplate engineのようなことを実装したサンプルのようなものも公開されているみたいです。

GitHub – ebrehault/superformatter
https://github.com/ebrehault/superformatter

repeatcallifに対応していて、次のような感じで使えます。

>>> from engine import SuperFormatter
>>> sf = SuperFormatter()
>>> print(sf.format('{n:repeat:n={{item}}\n}', n=[2,3,5,7]))
n=2
n=3
n=5
n=7

現状ではサンプル程度のものかと思いますが、面白そうなテクニックかなと思います。

リンク

string — Common string operations — Python 3.7.2 documentation
https://docs.python.org/3/library/string.html

The world’s simplest Python template engine — Makina Corpus
https://makina-corpus.com/blog/metier/2016/the-worlds-simplest-python-template-engine