字符串补位

7.1.6  插入和填充字符串
String类包含了在一个字符串中插入新元素的方法,可以用Insert在任意位置插入任意字符。而使用PadLeft/PadRight方法,可以在一个字符串的左右两侧进行字符填充。

1.Insert方法
Insert方法用于在一个字符串的指定位置插入另一个字符串,从而构造一个新的串。Insert方法也有多个重载形式,最常用的为:

public string Insert(int startIndex, string value);

其中,参数startIndex用于指定所要插入的位置,从0开始索引;value指定所要插入的字符串。下例中,在“Hello”的字符“H”后面插入“World”,构造一个串“HWorldello”。

代码7-12  使用Insert插入字符串示例:Class1.cs

1.              //Insert

2.              newStr="";

3.              newStr=strA.Insert(1,strB);

4.              Console.WriteLine(newStr);              //"HWorldello"

2.PadLeft/PadRight方法
有时候,可能需要对一个字符串进行填充,例如,想要把“Hello”变为长度为20个字符的串,并使用字符‘*’进行填充,即变为“***************Hello”。PadLeft方法可以实现这个功能,用于在一个字符串的左侧进行字符填充,使其达到一定的长度。PadLeft有两种重载形式。

     public string PadLeft(int totalWidth)

     public string PadLeft(int totalWidth, char paddingChar)

其中,参数totalWidth指定了填充后的字符长度,而paddingChar指定所要填充的字符,如果缺省,则填充空格符号。

下例中,实现了对“Hello”的填充操作,使其长度变为20。

代码7-13  使用PadLeft填充字符串示例:Class1.cs

1.              //PadLeft

2.              newStr="";

3.              newStr=strA.PadLeft(20,'*');

4.              Console.WriteLine(newStr);              //"***************Hello "

同PadLeft类似,PadRight可以实现对一个字符在其右侧的填充功能,对其不作赘述。

js 补位

<script type="text/javascript">
function padLeft(str, pad, count) 

{
while(str.length<count)
str
=pad+str;
return str;
}

function check(el) 

{
el.value
=padLeft(el.value.replace(/^(\d\d)$/,"$1"), "0"3);
}

</script>

原文地址:https://www.cnblogs.com/zhc088/p/892268.html