programing

int를 문자열로 변환하시겠습니까?

bestprogram 2023. 4. 12. 23:07

int를 문자열로 변환하시겠습니까?

변환하려면 어떻게 해야 하나요?int에 데이터 입력하다string데이터 입력은 C#에 있습니까?

string myString = myInt.ToString();
string a = i.ToString();
string b = Convert.ToString(i);
string c = string.Format("{0}", i);
string d = $"{i}";
string e = "" + i;
string f = string.Empty + i;
string g = new StringBuilder().Append(i).ToString();

만약 당신이 2진수 표현을 원한다면, 그리고 당신이 어젯밤 파티에서 취한 채로 있을 때를 대비해서:

private static string ByteToString(int value)
{
    StringBuilder builder = new StringBuilder(sizeof(byte) * 8);
    BitArray[] bitArrays = BitConverter.GetBytes(value).Reverse().Select(b => new BitArray(new []{b})).ToArray();
    foreach (bool bit in bitArrays.SelectMany(bitArray => bitArray.Cast<bool>().Reverse()))
    {
        builder.Append(bit ? '1' : '0');
    }
    return builder.ToString();
}

주의: 엔디안을 잘 다루지 못하는 것에 대해...


속도를 높이기 위해 메모리를 조금 희생해도 괜찮다면 아래를 사용하여 미리 계산된 문자열 값을 사용하여 어레이를 생성할 수 있습니다.

static void OutputIntegerStringRepresentations()
{
    Console.WriteLine("private static string[] integerAsDecimal = new [] {");
    for (int i = int.MinValue; i < int.MaxValue; i++)
    {
        Console.WriteLine("\t\"{0}\",", i);
    }
    Console.WriteLine("\t\"{0}\"", int.MaxValue);
    Console.WriteLine("}");
}
int num = 10;
string str = Convert.ToString(num);

임의의 객체의 ToString 메서드는 해당 객체의 문자열 표현을 반환합니다.

int var1 = 2;

string var2 = var1.ToString();

@Xavier의 답변에 더하여, 100회 반복에서 21474,836회 반복으로 변환하는 여러 가지 방법을 빠르게 비교할 수 있는 페이지를 소개합니다.

다음 두 가지 사이에 거의 관계가 있는 것 같습니다.

int someInt = 0;
someInt.ToString(); //this was fastest half the time
//and
Convert.ToString(someInt); //this was the fastest the other half the time
string str = intVar.ToString();

상황에 따라서는 를 사용할 필요가 없습니다.ToString()

string str = "hi " + intVar;

또는 다음과 같이 입력합니다.

string s = Convert.ToString(num);
using System.ComponentModel;

TypeConverter converter = TypeDescriptor.GetConverter(typeof(int));
string s = (string)converter.ConvertTo(i, typeof(string));

정수 표현식에 메서드를 적용할 수 있다는 응답이 없습니다.

Debug.Assert((1000*1000).ToString()=="1000000");

정수 리터럴까지

Debug.Assert(256.ToString("X")=="100");

이와 같은 정수 리터럴은 종종 잘못된 코딩 스타일(매직 번호)로 간주되지만 이 기능이 유용한 경우가 있습니다.

string s = "" + 2;

이렇게 좋은 일을 할 수 있어요.

string s = 2 + 2 + "you" 

결과는 다음과 같습니다.

'4명의 너'

데이터셋에서 얻을 수 있는

string newbranchcode = (Convert.ToInt32(ds.Tables[0].Rows[0]["MAX(BRANCH_CODE)"]) ).ToString();

언급URL : https://stackoverflow.com/questions/3081916/convert-int-to-string