将字符附加到字符串以使其固定长度 [英] Append characters to string to make it fixed length

查看:106
本文介绍了将字符附加到字符串以使其固定长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在整数字符串的开头附加一些字符。例如我的字符串是45

我想在0000000000000045之前追加十四点。

问题是,我的字符串长度可能会有所不同,可能是4字符,有时是3个或10个以上的字符。

我只想把它写成16个字符的字符串,在它之前加上0。

我怎么能这样做? />


我尝试了什么:



我这样做

(my_string).PadLeft(16,'0'); 





但它会失败如果长度超过10

解决方案

除了PadLeft之外,还值得将它保持为整数,并使用ToString将其填充为全长 只有当你想把它呈现给用户时:

  int  i =  45 ; 
string padded = i.ToString( D16\" );


例如number是一个45

的int,你想要一个长度为16个字符的字符串。



 var数= 45; 
var text = number.ToString(D16);





请看看这个

标准数字格式字符串| Microsoft Docs [ ^ ]


I want to append some characters in start of an integer string. for eg my string is "45"
I want to append fourteen 0 before it like 0000000000000045.
The problem is,my string's length may vary, it can be of 4 characters, sometimes 3 or more then 10 characters.
I just want to make it 16 characters string,by appending 0 before it.
how can I do this?

What I have tried:

I am doing this

(my_string).PadLeft(16 , '0');



but it will fail if length is more then 10

解决方案

In addition to PadLeft, it's worth keeping it as an integer number, and using ToString to "pad" it to the "full length" only when you want to present it to the user:

int i = 45;
string padded = i.ToString("D16");


e.g. number is an int of 45
and you want to have a string which is 16 characters long.

var number = 45;
var text = number.ToString("D16");



Please have a look at this
Standard Numeric Format Strings | Microsoft Docs[^]


这篇关于将字符附加到字符串以使其固定长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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