在字符串的第一个和最后一个位置插入字符 [英] Insert character at first and last position of a string

查看:1698
本文介绍了在字符串的第一个和最后一个位置插入字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在字符串变量中的第一个{和最后一个位置}插入一个字符。


str = str.Substring(0,1)+{+ str.Substring(1,str.Length)+};

我期望str ={1,2,3,4,5,6};



我没有得到结果。请帮帮我。

解决方案

您不需要使用 Substring 做工作:

  str ={+ str +}; 

另一个实现相同结果的常用方法是使用 string.Format

  str = string.Format({{{0}}},str); 

请注意 {} 需要加倍以便在 {0} 周围使用参数指示符作为文字大括号。


I am trying to insert a character at the first "{" and last position "}" in a string variable. My code is

string str = "1,2,3,4,5,6";  
str = str.Substring(0, 1) + "{" + str.Substring(1, str.Length) + "}";

I expect as str = "{1,2,3,4,5,6}";

I am not getting the result. Please help me.

解决方案

You do not need to use Substring at all: this should do the job:

str = "{" + str + "}";

Another common way of achieving the same result is with string.Format:

str = string.Format("{{{0}}}", str);

Note that { and } need to be doubled in order to be used around the {0} parameter designator as literal curly braces.

这篇关于在字符串的第一个和最后一个位置插入字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆