官术网_书友最值得收藏!

Positioning the output

One of the more useful extensions in C# is string.Format(...);. This allows for a string to be constructed based on parameters at particular positions. For example, the following statement constructs a string where the parameter at a position after the string literal is inserted into the string (here, the letter B is inserted twice in the middle of the string and then at the end):

var myString = string.Format("Hello {0}, I am a {1}{1}{2} computer model {1}", name, "B", "C"); 

Rust also supports this form, but with the difference that the positioning may be omitted.

Consider the following examples:

format!("{} {}", 2, 10); // output 2 10 
format!("{1} {} {0} {}", "B", "A"); 

The first example is what we've seen before. The format string gets filled with the parameters on the right, in order.

In the second example, it would seem that we're asking for four parameters, but have only supplied two. The way this works is that the positional arguments are ignored when filling in the non-positional arguments. Indexing, as is usual in programming, starts at zero. This is how the arguments are processed:

  • {1} inserts the second parameter A
  • {} inserts the first parameter B
  • {0} inserts the first parameter B
  • {} inserts the second parameter A

Therefore, the output is going to be A B B A.

The following are the two important rules governing the positional parameters:

  1. All of the arguments within the quotes must be used. Failure to do so will result in a compiler error.
  2. You can refer to the same argument as many times as you like within the format string.
主站蜘蛛池模板: 西充县| 新宾| 社会| 三台县| 巴马| 大兴区| 江源县| 讷河市| 五家渠市| 正定县| 屏东县| 德格县| 封丘县| 安丘市| 高唐县| 虹口区| 南投县| 晴隆县| 济南市| 平泉县| 安仁县| 华安县| 台中县| 温宿县| 汨罗市| 阿巴嘎旗| 清水河县| 上思县| 榆社县| 普陀区| 庆安县| 南充市| 小金县| 东丽区| 清流县| 道孚县| 长白| 乡宁县| 黄平县| 光山县| 德兴市|