Click here to Skip to main content
15,891,423 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all

I am printing in a text file

C#
string per = dt.Rows[i][2].ToString();
int l = per.Length;
string len1 = per.Substring(0, 16);
string len2 = per.Substring(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..
Posted
Comments
Rock (Multithreaded) 21-Feb-14 6:39am    
Hi...Snehasish_Nandy.
You can download a free Winform Control.
Windows 8 Style button control.

http://aruny408.blogspot.com/p/free-windows-8-style-button-control.html

Well if you really want to add spaces to make up the length then you could do this ...
C#
// 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
C#
// 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));
 
Share this answer
 
Comments
[no name] 21-Feb-14 22:21pm    
Thanks for the reply CHill60.
It worked..
but now i am thinking like assigning a starting and ending point for each column.
e.g i have 4 columns. Date, particular, debit, balance.
So like date should be from 0-10, then particular 12-40 like this..
please tell me how can i do this..
CHill60 22-Feb-14 7:47am    
Have a look at this article Handling Fixed-width Flat Files with .NET Custom Attributes[^]. If that's not quite what you want then try this http://trelford.com/blog/post/fixed.aspx[^]. If you go to google then use "c# fixed width file" to get a good set of results. Give it a go and if you hit any problems come back and post a new question (that way more people will see it and possibly help)
Please check this out...
C#
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);
                }
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900