StringAdditionOperator

はじめに

文字列を結合します。

プログラム

定義等

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
/*
  Adding Strings together

  Examples of how to add Strings together
  You can also add several different data types to String, as shown here:

  created 27 Jul 2010
  modified 2 Apr 2012
  by Tom Igoe

  This example code is in the public domain.

  https://www.arduino.cc/en/Tutorial/BuiltInExamples/StringAdditionOperator
*/

// declare three Strings:
String stringOne, stringTwo, stringThree;
 

String型 (クラス)の変数を定義します。

setup()

19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
void setup() {
  // initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  stringOne = String("You added ");
  stringTwo = String("this string");
  stringThree = String();
  // send an intro:
  Serial.println("\n\nAdding Strings together (concatenation):");
  Serial.println();
}
 

Serial.begin()を使いシリアルポートを初期化します。Leonardo向けに、シリアル接続が確立するのを待っています。

また、String型 変数の初期化を行います。クラス名と同じメソッド(この場合はString())はコンストラクタと呼ばれ、変数を初期化する際に利用します。

Serial.println()でシリアルポートに文字列を書き出します。

loop()

34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
void loop() {
  // adding a constant integer to a String:
  stringThree =  stringOne + 123;
  Serial.println(stringThree);    // prints "You added 123"

  // adding a constant long integer to a String:
  stringThree = stringOne + 123456789;
  Serial.println(stringThree);    // prints "You added 123456789"

  // adding a constant character to a String:
  stringThree =  stringOne + 'A';
  Serial.println(stringThree);    // prints "You added A"

  // adding a constant string to a String:
  stringThree =  stringOne +  "abc";
  Serial.println(stringThree);    // prints "You added abc"

  stringThree = stringOne + stringTwo;
  Serial.println(stringThree);    // prints "You added this string"

  // adding a variable integer to a String:
  int sensorValue = analogRead(A0);
  stringOne = "Sensor value: ";
  stringThree = stringOne  + sensorValue;
  Serial.println(stringThree);    // prints "Sensor Value: 401" or whatever value analogRead(A0) has

  // adding a variable long integer to a String:
  stringOne = "millis() value: ";
  stringThree = stringOne + millis();
  Serial.println(stringThree);    // prints "The millis: 345345" or whatever value millis() has

  // do nothing while true:
  while (true);
}

Stringクラスでオーバーライドした+(結合)を利用して、文字列を結合することができます。コンストラクタがint型やchar型にも対応しているので、さまざまな形式の値を結合することができます。

バージョン

Hardware:Arduino Uno
Software:Arduino 1.8.16

最終更新日

September 11, 2021

inserted by FC2 system