Arduino:
文字列の長さを求める
How to: (方法)
void setup() {
Serial.begin(9600);
String greeting = "こんにちは";
int length = greeting.length();
Serial.println(length);
}
void loop() {
// nothing to do here
}サンプル出力:
5Deep Dive (深掘り)
文字列の長さを見つけるにはStringクラスのlength()メソッドを使います。1980年代にC言語でのstrlen()関数の登場から、多くの言語がこれを実装してきました。Arduinoでもlength()は単純明快。ただし、Stringオブジェクトは動的メモリを使用するため、メモリフラグメンテーションのリスクがあります。このために、char配列とCスタイルの文字列関数を使うこともできます。ただし、使用方法は少し複雑です。
See Also (関連情報)
- ArduinoのStringリファレンス: https://www.arduino.cc/reference/en/language/variables/data-types/stringobject/
- メモリ管理についての情報: https://learn.arduino.cc/programming/best-practices/effective-use-of-memory
- C言語の文字列関数について: http://www.cplusplus.com/reference/cstring/