2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【C#】文字の抜粋と配列

Posted at

文字列の抜粋

前提条件
//abcde と入力
string str = Console.ReadLine();

以降それぞれのパターンを記載します。

配列の中身を抜粋する


前から数えて抜粋

ToCharArray()
//インデックス2番目を始点と数え、4つ抜粋する
char[] chArray = str.ToCharArray(2, 4);

Console.WriteLine(chArray);
//cdef
str.Substring()
//同上別のパターン
Console.WriteLine(str.Substring(2, 4));
//cdef
SubstringByTextElements()
//同上別のパターン
using System.Globalization;
...()

StringInfo str2 = new StringInfo(str);
Console.WriteLine(str2.SubstringByTextElements(2, 4));
//cdef
範囲演算子(「..」と表記されているもの)
char[] chArray = str.ToCharArray();

//インデックス2番目から3番目までを抜粋する(2以上4未満)
Console.WriteLine(chArray[2..4]);
//cd

仮に…
インデックスじゃなくて、数えでの2番目~4番目を抜粋したい。
範囲演算子「..」を使用しない場合。

数えで2番目から4番目を抜粋(2以上4以下)
char[] chArray = str.ToCharArray(2 - 1, 4 - 2 + 1);
Console.WriteLine(chArray);
//bcd
------------

//入力あり + 計算部分を置き換え

int num = int.Parse(Console.ReadLine());
//2
int num_2 = int.Parse(Console.ReadLine());
//4
char[] chArray = str.ToCharArray(num - 1, num_2 - num + 1)
//bcd

配列をコピーして抜粋

Array.Copy()
char[] chArray = str.ToCharArray();
char [] chArray_copy = new char[6];

//chArray[1]~の中身を、 chArray_copy[2]~[5]にコピー。
//(chArray_copyのインデックス2番目を含んだ、4つ分のインデックスにコピー)
//(つまりchArray_copy[2][3][4][5]の位置にコピーする)
 Array.Copy(chArray, 1, chArray_copy, 2, 4);

Console.WriteLine (chArray_copy);
//bcde

ちなみに、
Array.Copy()では参照元(コピー元)の値が変化しても影響を受けないです。

後ろから数えて抜粋

^
//後ろから数えて2番目を抜粋
Console.WriteLine(chArray[^2]) ;
//d

--- ### 入力した文字列を1文字ずつ配列に入れる ```C#: //例:a b c de f と入力 string str = Console.ReadLine();

char[] chArray = str.ToCharArray();
//[a][ ][b][ ][c][ ][d][e][ ][f]

空白ごと入ります。
<br><br>

```C#:
using System.Linq;
...(略)
char[] ch = str.ToArray();
//[a][ ][b][ ][c][ ][d][e][ ][f]

また、ToArry()でも同様に配列ができます。
この場合はusing System.Linq;を追加します。


入力した1文字が何番目にあるか探す

//例;abcde と入力
string str = Console.ReadLine();

char [] chArry = str.ToCharArray();

//探したい文字をひとつ入力
int str2 = Console.Read();
//b

 for (int i = 0; i < str.Length; i++) {
     if ((char)str2 == chArry[i]) {
Console.WriteLine(i + 1);
//2
      }
    }

bという文字が2番目にあることが分かります。

参考にしたサイト

String.ToCharArray メソッド
StringInfo.SubstringByTextElements メソッド0
インデックスと範囲
Array.Copy メソッド

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?