在c#中为字符串添加空格

在c#中为字符串添加空格

本文介绍了在c#中为字符串添加空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好



我在一个文本文件中打印



Hi all

I am printing in a text file

string per = dt.Rows[i][2].ToString();
int l = per.Length;
string len1 = per.Substring(0, 16);
string len2 = per.Substring(16);





这是我的2个字符串。



问题如果字符串 小于16,例如12,

它显示错误。



所以我想要的是如果字符串小于16那么它会添加剩余的空格来制作它是16.

如果它超过16则没什么..



请告诉我该怎么做..



this is my 2 strings.

problem is if the string "per" is less then 16 e.g. 12,
it's showing error.

So what i want to if the string is less then 16 then it will add remaining spaces to make it 16.
if it's more then 16 then nothing..

Please tell me how to do this..

推荐答案

// method 1 - pad right with spaces first
per = per.PadRight(16);
// using TrimEnd in the next line effectively implements your requirement "if it's more than 16 then nothing"
len1 = per.Substring(0, 16).TrimEnd();
len2 = per.Substring(16).TrimEnd();



或者如果你是只关心那个错误然后我认为这更好


Or if you are just concerned about that error then I think this is better

// method 2 - no spaces added at end, handles any length string including 0
string len1 = per.Substring(0, Math.Min(16, per.Length));
string len2 = per.Substring(Math.Min(16, per.Length));


string per = dt.Rows[i][2].ToString();
                if (per.Length >= 16)
                {
                    string len1 = per.Substring(0, 16);
                    Console.Write("len1: " + len1);
                }
                else
                {
                    string len2 = per.Substring(0, per.Length);
                    Console.Write("len2:" + len2);
                }


这篇关于在c#中为字符串添加空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 00:32