2019年3月5日火曜日

文字列の扱いではまるポイント

Powershellが期待通りに動かずハマるポイント…
変数の型宣言が無くて楽だけど、いざというときにハマるポイントです。
Powershellに限らず、変数の型宣言が無い言語はみんな同じだと思う。
先ずは…文字、文字列、文字列配列の違いが分かってることが前提です。

# 文字列配列で間違いやすいポイント

# どれが文字列配列か
# ★実際に実行してみてね
## 変数
$String1 = 'これは文字列です。'         # 1つの文字列
$String2 = ('これも文字列です。')       # ()は先に処理するだけ。ここだと無いのと同じ。
$String3 = @('これは文字列配列です')    # @()は配列お宣言。中身が文字列なので、文字列配列
$String4 = @()                      # @()は配列お宣言。配列で初期化
$String4 += 'これも文字列配列です'      # 文字列を配列に追加
$String5 = 'じゃあ…これは?','これは文字列配列です。' # 2つの文字列なので、文字列配列になる。
## 配列長
$String1.Length
$String2.Length
$String3.Length
$String4.Length
$String5.Length
## 1つ目の配列の中身…
$String1[0]     # 文字列(文字配列)なので、1文字目を表示
$String2[0]     # 文字列(文字配列)なので、1文字目を表示
$String3[0]     # 文字列配列なので、1行目を表示
$String4[0]     # 文字列配列なので、1行目を表示
$String5[0]     # 文字列配列なので、1行目を表示

## 演算子の結果だと…
$String1 -match '文字'
$String5 -match '文字'
$String1 -match '?'
$String5 -match '?'
$String1 -match 'これ'
$String5 -match 'これ'
$String1 -ne 'a'
$String5 -ne 'a'

### ↑この結果の違いが理解できないと、バグを埋め込むことになります。
### 文字列として扱いたいのか、文字列配列として扱いたいのかを意識して扱うこと。

@($String1) -match '文字'   # 文字列配列化
$String5[0] -match '文字'   # 文字列配列の1つ目の文字列
$String5[1] -match '文字'   # 文字列配列の2つ目の文字列

2 件のコメント:

  1. All Slots.info - Wooricainos
    Our Best Online Slots for UK Players ✓ Try New Slot Games The list of sbobet all 룰렛돌리기 the online slots bitcasino casinos available at 스포츠토토 하는법 All Slots.info is one that 피망 슬롯 머신 has made

    返信削除
  2. At Potawatomi Hotel & Casino,blackjackis performed with multiple of} decks of playing cards and is dealt from a shoe. Double Deck Blackjack sport is nearly of} a lot as good} as Single Deck Blackjack, and in the case of our casino, it’s even higher. That’s as a result of|as a outcome of} our Double Deck Blackjack requires the supplier to stand 코인카지노 on soft 17 – a rule that favors players. One perceived shortcoming by the casino executive is that the facet bets slow down the game. However, the game would solely slow down when the bets are wagered. When wagered, the higher mathematical benefit of the facet bet more than makes up for any slight sport tempo discount.

    返信削除