0
1

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 1 year has passed since last update.

C#で文字コードがShift-JISのString配列をUTF-8に変換する方法

Last updated at Posted at 2023-07-07

はじめに

昨日、CSVから文字コード「shift-jis」のデータを取得しようとした際、躓いたので、
文字コードがShift-JISのString配列をUTF-8に変換する方法について解説します。

Shift-JISの文字列の取得方法

まずは、Shift-JISの文字列を取得する方法について説明します。以下のコードを使用します。

string shiftJisString = "こんにちは、世界!";
byte[] shiftJisBytes = Encoding.GetEncoding("Shift-JIS").GetBytes(shiftJisString);

上記のコードでは、Encoding.GetEncoding("Shift-JIS")を使用してShift-JISのエンコーディングを取得し、GetBytes()メソッドを使用してShift-JISの文字列をバイト配列に変換しています。

Shift-JISのString配列をUTF-8に変換する方法

次に、Shift-JISのString配列をUTF-8に変換する方法について説明します。以下のコードを使用します。

string[] shiftJisArray = { "こんにちは", "世界" };

List<byte[]> utf8ByteArrays = new List<byte[]>();
var shiftjis = Encoding.GetEncoding("Shift-JIS");
foreach (string shiftJisString in shiftJisArray)
{
    byte[] shiftJisBytes = shiftjis.GetBytes(shiftJisString);
    byte[] utf8Bytes = Encoding.Convert(shiftjis, Encoding.UTF8, shiftJisBytes);
    utf8ByteArrays.Add(utf8Bytes);
}

List<string> utf8Strings = utf8ByteArrays.Select(bytes => Encoding.UTF8.GetString(bytes)).ToList();

上記のコードでは、Encoding.Convert()メソッドを使用してShift-JISのバイト配列をUTF-8に変換しています。変換後のUTF-8のバイト配列はutf8ByteArraysに格納されます。最後に、Encoding.UTF8.GetString()メソッドを使用してUTF-8のバイト配列を文字列に変換し、utf8Stringsに格納しています。

0
1
1

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?