IT story

왜 String.Format을 사용합니까?

hot-time 2020. 5. 27. 07:40
반응형

왜 String.Format을 사용합니까? [복제]


이 질문에는 이미 답변이 있습니다.

String.Format연결 연산자 ( &VB 및 +C #) 달리 C # 및 VB .NET에서 누군가를 사용하는 이유는 무엇 입니까?

주요 차이점은 무엇입니까? 왜 모두가 그렇게 사용하는데 관심이 String.Format있습니까? 매우 궁금합니다.


여러 가지 이유가 있습니다.

가독성

string s = string.Format("Hey, {0} it is the {1}st day of {2}.  I feel {3}!", _name, _day, _month, _feeling);

vs :

string s = "Hey," + _name + " it is the " + _day + "st day of " + _month + ".  I feel " + feeling + "!";

형식 지정자 (사용자 지정 형식기를 작성할 수 있다는 사실이 포함됨)

string s = string.Format("Invoice number: {0:0000}", _invoiceNum);

vs :

string s = "Invoice Number = " + ("0000" + _invoiceNum).Substr(..... /*can't even be bothered to type it*/)

문자열 템플릿 지속성

데이터베이스에 문자열 템플릿을 저장하려면 어떻게합니까? 문자열 형식으로 :

_id         _translation
  1         Welcome {0} to {1}.  Today is {2}.
  2         You have {0} products in your basket.
  3         Thank-you for your order.  Your {0} will arrive in {1} working days.

vs :

_id         _translation
  1         Welcome
  2         to
  3         .  Today is
  4         . 
  5         You have
  6         products in your basket.
  7         Someone
  8         just shoot
  9         the developer.

조금 더 읽기 쉽고 연산자를 더 추가하는 것 외에도 응용 프로그램이 국제화되어있는 경우에도 유용합니다. 많은 경우 변수는 언어 나 언어에 따라 순서가 다른 숫자 나 키워드입니다. String.Format을 사용하면 코드가 변경되지 않고 다른 문자열이 리소스 파일로 이동합니다. 따라서 코드는

String.Format(resource.GetString("MyResourceString"), str1, str2, str3);

리소스 문자열이 끝나는 동안

영어: "blah blah {0} blah blah {1} blah {2}"

러시아인: "{0} blet blet blet {2} blet {1}"

러시아어가 물건을 처리하는 방법에 대해 다른 규칙을 가질 수 있으므로 순서가 다르거 나 문장 구조가 다릅니다.


먼저

string s = String.Format(
    "Your order {0} will be delivered on {1:yyyy-MM-dd}. Your total cost is {2:C}.",
    orderNumber,
    orderDeliveryDate,
    orderCost
);

읽기, 쓰기 및 유지 관리가 훨씬 쉽습니다.

string s = "Your order " +
           orderNumber.ToString() +
           " will be delivered on " +
           orderDeliveryDate.ToString("yyyy-MM-dd") +
           "." +
           "Your total cost is " +
           orderCost.ToString("C") + 
           ".";

다음이 얼마나 유지 관리가 가능한지보십시오

string s = String.Format(
    "Year = {0:yyyy}, Month = {0:MM}, Day = {0:dd}",
    date
);

date세 번 반복 해야하는 대안에 대해 .

Second, the format specifiers that String.Format provides give you great flexibility over the output of the string in a way that is easier to read, write and maintain than just using plain old concatenation. Additionally, it's easier to get culture concerns right with String.Format.

Third, when performance does matter, String.Format will outperform concatenation. Behind the scenes it uses a StringBuilder and avoids the Schlemiel the Painter problem.


Several reasons:

  1. String.Format() is very powerful. You can use simple format indicators (like fixed width, currency, character lengths, etc) right in the format string. You can even create your own format providers for things like expanding enums, mapping specific inputs to much more complicated outputs, or localization.
  2. You can do some powerful things by putting format strings in configuration files.
  3. String.Format() is often faster, as it uses a StringBuilder and an efficient state machine behind the scenes, whereas string concatenation in .Net is relatively slow. For small strings the difference is negligible, but it can be noticable as the size of the string and number of substituted values increases.
  4. String.Format() is actually more familiar to many programmers, especially those coming from backgrounds that use variants of the old C printf() function.

Finally, don't forget StringBuilder.AppendFormat(). String.Format() actually uses this method behind the scenes*, and going to the StringBuilder directly can give you a kind of hybrid approach: explicitly use .Append() (analogous to concatenation) for some parts of a large string, and use .AppendFormat() in others.


* [edit] Original answer is now 8 years old, and I've since seen an indication this may have changed when string interpolation was added to .Net. However, I haven't gone back to the reference source to verify the change yet.


String.Format adds many options in addition to the concatenation operators, including the ability to specify the specific format of each item added into the string.

For details on what is possible, I'd recommend reading the section on MSDN titled Composite Formatting. It explains the advantage of String.Format (as well as xxx.WriteLine and other methods that support composite formatting) over normal concatenation operators.


There's interesting stuff on the performance aspects in this question

However I personally would still recommend string.Format unless performance is critical for readability reasons.

string.Format("{0}: {1}", key, value);

Is more readable than

key + ": " + value

For instance. Also provides a nice separation of concerns. Means you can have

string.Format(GetConfigValue("KeyValueFormat"), key, value);

And then changing your key value format from "{0}: {1}" to "{0} - {1}" becomes a config change rather than a code change.

string.Format also has a bunch of format provision built into it, integers, date formatting, etc.


One reason it is not preferable to write the string like 'string +"Value"+ string' is because of Localization. In cases where localization is occurring we want the localized string to be correctly formatted, which could be very different from the language being coded in.

For example we need to show the following error in different languages:

MessageBox.Show(String.Format(ErrorManager.GetError("PIDV001").Description, proposalvalue.ProposalSource)

where

'ErrorCollector.GetError("ERR001").ErrorDescription' returns a string like "Your ID {0} is not valid". This message must be localized in many languages. In that case we can't use + in C#. We need to follow string.format.

참고URL : https://stackoverflow.com/questions/4671610/why-use-string-format

반응형