---
title: "固定字符串长度，不足补空格"
author: "ch.net"
date: "2008-10-23T20:48:44Z"
tags: ["C", "C#", "C++", "SQL"]
slug: "untitled"
draft: false
lastmod: "2008-10-23T20:48:44Z"
id: 257165
url: "https://haha-net.iteye.com/blog/257165"
---

**C#**

 

在字串左（或右）加空格或指定char字符，使字串达到指定长度，如：  
&lt;%  
string str1="中国人";  
str1=str1.PadLeft(10,'1'); //无第二参数为加空格  
Response.Write(str1); //结果为“1111111中国人” ， 字串长为10  
%&gt;

 

 

**sql**

 

方法1：

 

declare  
 @a nvarchar(50),  
 @b nvarchar(50)  
set @a = 'abcasdf'  
set @b = 'ab'  
select @a + space(20 - len(@a))  
select @b + space(20 - len(@b))

 

注：space ( 参数&gt;=0 ),           补的空格数, 不能超过字符数，下同

 

 

方法2：

 

declare  
 @aa nvarchar(200)  
set @aa = 'sgawe'

select @aa + replicate(' ', 40 - datalength(@aa))