I have a string, and I want to add a number of spaces to the beginning of that string based on an int variable.
I want to do something like this:
int NumberOfTabs = 2;
string line = "my line";
string line = String.Format("{0}{1}", " " * NumberOfTabs, line);
...and now line would have 8 spaces
What is the easiest way to do this?
You can use the String(char, Int32) constructor like this:
string line = String.Format("{0}{1}", new String(' ', NumberofTabs * 4), line);
or a bit more efficient:
string line = String.Concat(new String(' ', NumberofTabs * 4), line);
or, a bit more concise :)
string line = new String(' ', NumberofTabs * 4).Concat(line);
A comment made a good point, if you want to actually have the tab character, just change the ' ' to '\t' and take out the * 4 like this:
string line = String.Concat(new String('\t', NumberofTabs), line);
int i=8;
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(" ", i);
new string(' ', NumberOfTabs )
str = str.PadLeft(str.Length+tabs*4);
In C# strings are immutable. You should really use the stringbuilder class.
Code examples are listed in the link:
http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx
You could use something like this:
String.Empty.PadRight(NumberOfTabs)
You can add tabs at the beginning of your text like this:
line.PadLeft(NumberOfTabs, '\t');
\t being the escape character for "tab"
(Inserting a tab character into text using C#)
int NumberOfTabs = 2;
string line = "my line";
string results = line.PadLeft(line.Length + NumberOfTabs, ' ');
Not the best answer by any measure, but here's an amusing one, a little LINQ one-liner:
var result = new string(Enumerable.Repeat(' ', count).Concat("my line").ToArray());
You can create a new string containing a custom number of spaces. Unfortunately, there's no string multiplication like in Python (" " * 2). But you can multiply the number of spaces by 4 to get "tabs":
int numberOfTabs = 2;
string line = "my line";
string whitespaces = new string(' ', numberOfTabs * 4);
string s = whitespaces + line;
Related
const string Duom = "Text.txt";
char[] seperators = { ' ', '.', ',', '!', '?', ':', ';', '(', ')', '\t' };
string[] lines = File.ReadAllLines(Duom, Encoding.GetEncoding(1257));
for (int i = 0; i < lines.Length; i++)
{
string GLine = " " + lines[i];
GLine = Regex.Replace(GLine, #"\s+", " ");
GLine = GLine.PadRight(5, ' ');
Console.WriteLine(GLine);
}
Reads a text file, for each line it adds a whitespace at the start, removes all double and above whitespaces, and I want to move the line to the right , but it doesn't do anything.
Result :
Expected Result:
PadLeft and PadRight doesn't add characters to the start/end of your string if the specified length has already been reached.
From the docs for String.PadRight (emphasis mine):
Returns a new string that left-aligns the characters in this string by padding them on the right with a specified Unicode character, for a specified total length.
All of your strings are larger than 5, the specified total length, so PadRight/PadLeft won't do anything.
"Padding" the string is adding spaces (or some other character) so that the new string is at least as large as the number you want.
Instead, just manually add 5 spaces before your string.
GLine = " " + GLine;
Or more programmaticly:
GLine = new string(' ', 5) + GLine;
You could replace the body of your loop like this:
string GLine = new string(' ', 1 + i * 5) + Regex.Replace(lines[i], #"\s+", " ");
Console.WriteLine(GLine);
This will add 1 space and then 5 more spaces for each line.
for (int i = 0; i < lines.Count(); i++)
{
string GLine = new string(' ',5*i) + lines[i];
Console.WriteLine(GLine);
}
This should add 5 extra spaces for each line you have, which i believe is what you are trying to accomplish if i understand correctly.
You need to left pad a tab depending on how many lines of text you have. The best increment to use is the i variable.
string GLine = " " + lines[i];
change this to
string GLine = new String('\t', i) + lines[i];
By the way, PadLeft should work but keep in mind you need to execute it i times
Hello I've created some C# code that is writing to a .txt file using a StringBuilder object, everything seems OK, but the problem is that I need exactly 200 characters for each line. For example, when the program sets a string variable value of 10 characters in a line (this value varies in the number characters), that line must contain 190 blank spaces. This is an example of the code that I have:
if (File.Exists(DLFile))
{
using (StreamWriter sw = new StreamWriter(DLFile))
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append("001" + partNumber + " ").AppendLine();
String innerString = stringBuilder.ToString();
sw.WriteLine(innerString);
sw.Close();
}
}
There is a string variable named 'partNumber' that varies in length. Sometimes the length can be 15 or 14 or 10, but the sum of this length and the blank spaces may be 200 (exact quantity). Can anyone help me with this?
Just use PadRight (Or PadLeft if appropriate) as it's designed to do exactly this.
sw.WriteLine(("001" + partNumber).PadRight(200));
Sure. Just take a look at the String.format method, and specify the format to achieve this.
In your case, it means doing something like:
string line = String.Format("{0,-200}", input);
How about simply calculating and then using this overload?:
...
var h = "001" + partNumber;
stringBuilder.Append( h );
stringBuilder.Append( ' ', 200 - h.Length );
...
To make it (a bit) more error-proof:
...
var h = "001" + partNumber;
stringBuilder.Append( h );
var a = 200 - h.Length;
if ( a > 0 )
{
stringBuilder.Append( ' ', a );
}
...
You can use this string constructor to repeat white-spaces:
int whiteSpacesLength = 200 - partNumber.Length; // assuming partNumber is never > 200
string whiteSpaces = new String(' ', whiteSpacesLength);
string innerString = partNumber + whiteSpaces;
Demo
( so i see no reason to use a StringBuilder here)
use a defined string with 200 spaces and then do a substring as below
string space200 = " ";
if (File.Exists(DLFile))
{
using (StreamWriter sw = new StreamWriter(DLFile))
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append("001").Append(partNumber).Append(space200.Substring(stringBuilder.ToString().Length, space200.Length - stringBuilder.ToString().Length)).AppendLine();
String innerString = stringBuilder.ToString();
sw.WriteLine(innerString);
sw.Close();
}
}
I have a string let say,
string temp1 = "25 10 2012"
but I want this,
"2012 10 25"
what would be the best way of doing it. format will always be like this.
Looks like its a date. You can parse the string to DateTime, using DateTime.ParseExact and then use .ToString to return formatted result.
DateTime dt = DateTime.ParseExact(temp1, "dd MM yyyy", CultureInfo.InvariantCulture);
Console.Write(dt.ToString("yyyy MM dd"));
You may use that DateTime object later in your code, and also apply different formatting (if you need)
try this split string and reverse array , and this will work for string of any length ...
string[] myArray = temp1.Split(' ');
Array.Reverse( myArray );
string reverse =string.Join(" ", myArray );
You could do it using the Split command and then recombining the sub strings:
String[] subStrs = temp1.Split( ' ' );
String final = subStrs[2] + " " + subStrs[1] + " " + subStrs[0];
So you want to split words and change the order, you can use LINQ:
var words = temp1.Split(' ');
String newWord = string.Join(" ", words.Reverse());
or if you don't want to swap all words but only swap the first and last word:
String first = words.Last();
String last = words.First();
String newWord = first + " "
+ string.Join(" ", words.Skip(1).Take(words.Length - 2))
+ " " + last;
You could either use a RegEx or split the string and rejoin it in reverse order.
string s = "2012 10 25";
string[] tokens = s.Split(' ');
Array.Reverse(tokens);
string final = string.Join(" ", tokens);
If Your string has always 10 character (with spaces), You can do the following:
string str = "26 10 2012"
str = str.Substring(6, 4) + " " + str.Substring(3, 2) + " " + str.Substring(0, 2)
you can use string.split(" ").reverse().join(" ").
You can use split, this function will split your string to array on white space as condition then reverse the array and re join based on white space
let string="25 10 2012";
let output=string.split(" ").reverse().join(" ");
console.log(output)
I would like to format a string that looks like this
BPT4SH9R0XJ6
Into something that looks like this
BPT4-SH9R-0XJ6
The string will always be a mix of 12 letters and numbers
Any advice will be highly appreciated, thanks
Try Regex.Replace(input, #"(\w{4})(\w{4})(\w{4})", #"$1-$2-$3");
Regex is often derided, but is a pretty neat way of doing what you need. Can be extended to more complex requirements that are difficult to meet using string methods.
You can use "(.{4})(.{4})(.{4})" as your expression and "$1-$2-$3" as your replacement. This is, however, hardly a good use for regexp: you can do it much easier with Substring.
var res = s.Substring(0,4)+"-"+s.Substring(4,4)+"-"+s.Substring(8);
If the rule is to always split in three block of four characters no need for a reg exp:
str.Substring(0,4) + "-" + str.Substring(4,4) + "-" + str.Substring(8,4)
It would seem that a combination of String.Concat and string.Substring should take care of everything that you need.
var str = "BPT4SH9R0XJ6";
var newStr = str.Substring(0, 4) + "-" + str.Substring(4, 4) + "-" + str.Substring(8, 4);
Any reason you want to do a regex? you could just insert hyphens:
string s = "BPT4SH9R0XJ6";
for(int i = 4; i < s.length; i = i+5)
s = s.Insert(i, "-");
This would keep adding hyphens every 4 characters, would not error out if string was too short/long/etc.
return original_string.SubString(0,4)+"-"+original_string.SubString(4,4)+"-"+original_string.SubString(8,4);
string str = #"BPT4SH9R0XJ6";
string formattedString = string.Format("{0}-{1}-{2}", str.Substring(0, 4), str.Substring(4,4), str.Substring(8,4));
This works with any length of string:
for (int i = 0; i < (int)Math.Floor((myString.Length - 1) / 4d); i++)
{
myString = myString.Insert((i + 1) * 4 + i, "-");
}
Ended upp using this
var original = "BPT4SH9R0XJ6".ToCharArray();
var first = new string(original, 0, 4);
var second = new string(original, 4, 4);
var third = new string(original, 8, 4);
var mystring = string.Concat(first, "-", second, "-", third);
Thanks
If you are guaranteed the text you're operating on is the 12 character code then why don't you just use substring? Why do you need the Regex?
String theString = "AB12CD34EF56";
String theNewString = theString.Substring(0, 4) + "-" + theString.Substring(4, 4) + "-" + theString.Substring(8, 4);'
I want to trim the end off a string if it ends in ", ". That's a comma and a space.
I've tried TrimEnd(', '), but this doesn't work. It has to be only if the string ends this way, so I can't just use .Remove to remove the last two characters. How can I do it?
string txt = " testing, , ";
txt = txt.TrimEnd(',',' '); // txt = "testing"
This uses the overload TrimEnd(params char[] trimChars). You can specify 1 or more chars that will form the set of chars to remove. In this case comma and space.
This should work:
string s = "Bar, ";
if (s.EndsWith(", "))
s = s.Substring(0, s.Length - 2);
EDIT
Come to think of it, this would make a nice extension method:
public static String RemoveSuffix(this string value, string suffix)
{
if (value.EndsWith(suffix))
return value.Substring(0, value.Length - suffix.Length);
return value;
}
Try this:
string someText = "some text, ";
char[] charsToTrim = { ',', ' ' };
someText = someText.TrimEnd(charsToTrim);
Works for me.
The catch is that mystring.Trim(',') will only work if you reassign it to the string itself like this:
mystring = mystring.Trim(',')
"value, ".Trim().TrimEnd(",") should also work.
if (model != null && ModelState.IsValid)
{
var categoryCreate = new Categories
{
CategoryName = model.CategoryName.TrimStart().TrimEnd(),
Description = model.Description.TrimStart().TrimEnd()
};
_CategoriesService.Create(categoryCreate);
}
TrimStart().TrimEnd() == Left Trim and Right Trim