I'm getting a string as a parameter.
Every string should take 30 characters and after I check its length I want to add whitespaces to the end of the string.
E.g. if the passed string is 25 characters long, I want to add 5 more whitespaces.
The question is, how do I add whitespaces to a string?
You can use String.PadRight for this.
Returns a new string that left-aligns the characters in this string by padding them with spaces on the right, for a specified total length.
For example:
string paddedParam = param.PadRight(30);
You can use String.PadRight method for this;
Returns a new string of a specified length in which the end of the
current string is padded with spaces or with a specified Unicode
character.
string s = "cat".PadRight(10);
string s2 = "poodle".PadRight(10);
Console.Write(s);
Console.WriteLine("feline");
Console.Write(s2);
Console.WriteLine("canine");
Output will be;
cat feline
poodle canine
Here is a DEMO.
PadRight adds spaces to the right of strings. It makes text easier to
read or store in databases. Padding a string adds whitespace or other
characters to the beginning or end. PadRight supports any character
for padding, not just a space.
Use String.PadRight which will space out a string so it is as long as the int provided.
var str = "hello world";
var padded = str.PadRight(30);
// padded = "hello world "
you can use Padding in C#
eg
string s = "Example";
s=s.PadRight(30);
I hope It will resolve your problem.
Related
Im trying to split this string:
PublishDate: "2011-03-18T11:08:07.983"
I tried Split method but it's not successful.
str.Split(new[] { ':', ' ' }, StringSplitOptions.RemoveEmptyEntries)
As a result I get PublishDate 2011-03-18T11 08 07.983
But correct result is PublishDate 2011-03-18T11:08:07.983
What i need to do?
Split(String, Int32, StringSplitOptions)
Splits a string into a maximum number of substrings based on a specified delimiting string and, optionally, options.
str.Split(':', 2, StringSplitOptions.RemoveEmptyEntries)
https://learn.microsoft.com/en-us/dotnet/api/system.string.split?view=net-6.0#system-string-split(system-string-system-int32-system-stringsplitoptions)
I would solve like this:
locate the index of the first :. The property name will be all the characters before this, which you can extract with Substring and Trim to remove whitespace before the colon, if present.
locate the index of the first " and last ". Characters between the first and last quotes are the property value.
string input = "PublishDate: \"2011-03-18T11:08:07.983\"";
int iColon = input.IndexOf(':');
int iOpenQuote = input.IndexOf('"', iColon);
int iCloseQuote = input.LastIndexOf('"');
string propertyName = input.Substring(0, iColon).Trim();
string propertyValue = input.Substring(iOpenQuote + 1, iCloseQuote - iOpenQuote - 1);
This does not handle escaped characters within the property value (for example, to embed a literal quote or newline using a typical escape sequence like \" or \n). But it's likely good enough to extract a date/time string, and permits all characters because of the use of LastIndexOf. However, this is not robust against malformed input, so you will want to add checks for missing colon, or missing quote, or what happens when the close quote is missing (same same index for start and end quote).
So if I got you right, you want as a result: PublishDate 2011-03-18T11:08:07.983.
Then I would recommend you to use the string.Replace method.
using System;
public class HelloWorld
{
public static void Main(string[] args)
{
string yourData = "PublishDate: \"2011-03-18T11:08:07.983\"";
// First replace the colon and the space after the PublishDate with and space
// then replace the quotes from the timestamp -> "2011-03-18T11:08:07.983"
yourData = yourData.Replace(": ", " ").Replace("\"", "");
// Output the result -> PublishDate 2011-03-18T11:08:07.983
Console.WriteLine(yourData);
}
}
How can I concatenate the string "\u" with "a string" to get "\u0000"?
My code creates two backslashes:
string a = #"\u" + "0000"; //ends up being "\\\u0000";
The escape sequence \uXXXX is part of the language's syntax and represents a single Unicode character. By contrast, #"\u" and "0000" are two different strings, with a total of six characters. Concatenating them won't magically turn them into a single Unicode escape.
If you're trying to convert a Unicode code point into a single-character string, do this:
char.ConvertFromUtf32(strUnicodeOfMiddleChar).ToString()
BTW, don't use == true; it's redundant.
If I understand you correctly, I think you want to build a single-char string from an arbitrary Unicode value (4 hex digits). So given the string "0000", you want to convert that into the string "\u0000", i.e., a string containing a single character.
I think this is what you want:
string f = "0000"; // Or whatever
int n = int.Parse(f, NumberStyles.AllowHexSpecifier);
string s = ((char) n).ToString();
The resulting string s is "\u0000", which you can then use for your search.
(With corrections suggested by Thomas Levesque.)
the line below creates tow backslash:
string a = #"\u" + "0000"; //a ends up being "\\u0000";
No, it doesn't; the debugger shows "\" as "\", because that's how you write a backslash in C# (when you don't prefix the string with #). If you print that string, you will see \u0000, not \\u0000.
Nope, that string really has single backslash in. Print it out to the console and you'll see that.
Escape your characters correctly!!
Both:
// I am an escaped '\'.
string a = "\\u" + "0000";
And:
// I am a literal string.
string a = #"\u" + "0000";
Will work just fine. But, and I am going out on a limb here, I am guessing that you are trying to escape a Unicode Character and Hex value so, to do that, you need:
// I am an escaped Unicode Sequence with a Hex value.
char a = '\uxxxx';
Say I have a string such as
abc123def456
What's the best way to split the string into an array such as
["abc", "123", "def", "456"]
string input = "abc123def456";
Regex re = new Regex(#"\D+|\d+");
string[] result = re.Matches(input).OfType<Match>()
.Select(m => m.Value).ToArray();
string[] result = Regex.Split("abc123def456", "([0-9]+)");
The above will use any sequence of numbers as the delimiter, though wrapping it in () says that we still would like to keep our delimiter in our returned array.
Note: In the example snippet we will get an empty element as the last entry of our array.
The boundary you look for can be described as "A position where a digit follows a non-digit, or where a non-digit follows a digit."
So:
string[] result = Regex.Split("abc123def456", #"(?<=\D)(?=\d)|(?<=\d)(?=\D)");
Use [0-9] and [^0-9], respectively, if \d and \D are not specific enough.
Add space around digitals, then split it. So there is the solution.
Regex.Replace("abc123def456", #"(\d+)", #" \1 ").Split(' ');
I hope it works.
You could convert the string to a char array and then loop through the characters. As long as the characters are of the same type (letter or number) keep adding them to a string. When the next character no longer is of the same type (or you've reached the end of the string), add the temporary string to the array and reset the temporary string to null.
I have the following input:
string txt = " i am a string "
I want to remove space from start of starting and end from a string.
The result should be: "i am a string"
How can I do this in c#?
String.Trim
Removes all leading and trailing white-space characters from the current String object.
Usage:
txt = txt.Trim();
If this isn't working then it highly likely that the "spaces" aren't spaces but some other non printing or white space character, possibly tabs. In this case you need to use the String.Trim method which takes an array of characters:
char[] charsToTrim = { ' ', '\t' };
string result = txt.Trim(charsToTrim);
Source
You can add to this list as and when you come across more space like characters that are in your input data. Storing this list of characters in your database or configuration file would also mean that you don't have to rebuild your application each time you come across a new character to check for.
NOTE
As of .NET 4 .Trim() removes any character that Char.IsWhiteSpace returns true for so it should work for most cases you come across. Given this, it's probably not a good idea to replace this call with the one that takes a list of characters you have to maintain.
It would be better to call the default .Trim() and then call the method with your list of characters.
You can use:
String.TrimStart - Removes all leading occurrences of a set of characters specified in an array from the current String object.
String.TrimEnd - Removes all trailing occurrences of a set of characters specified in an array from the current String object.
String.Trim - combination of the two functions above
Usage:
string txt = " i am a string ";
char[] charsToTrim = { ' ' };
txt = txt.Trim(charsToTrim)); // txt = "i am a string"
EDIT:
txt = txt.Replace(" ", ""); // txt = "iamastring"
I really don't understand some of the hoops the other answers are jumping through.
var myString = " this is my String ";
var newstring = myString.Trim(); // results in "this is my String"
var noSpaceString = myString.Replace(" ", ""); // results in "thisismyString";
It's not rocket science.
txt = txt.Trim();
Or you can split your string to string array, splitting by space and then add every item of string array to empty string.
May be this is not the best and fastest method, but you can try, if other answer aren't what you whant.
text.Trim() is to be used
string txt = " i am a string ";
txt = txt.Trim();
Use the Trim method.
static void Main()
{
// A.
// Example strings with multiple whitespaces.
string s1 = "He saw a cute\tdog.";
string s2 = "There\n\twas another sentence.";
// B.
// Create the Regex.
Regex r = new Regex(#"\s+");
// C.
// Strip multiple spaces.
string s3 = r.Replace(s1, #" ");
Console.WriteLine(s3);
// D.
// Strip multiple spaces.
string s4 = r.Replace(s2, #" ");
Console.WriteLine(s4);
Console.ReadLine();
}
OUTPUT:
He saw a cute dog.
There was another sentence.
He saw a cute dog.
You Can Use
string txt = " i am a string ";
txt = txt.TrimStart().TrimEnd();
Output is "i am a string"
I need to shorten a string down..
Lets say we have a string with the length 500.
I only want the first part of it - max 180 characters, ending with the last word before reaching the 180. I don't want to cut the string short in the middle of a word.
How is this achived? it does not have to perform all that well.. it is something that happens a couple of times a day, not more.
A really easy way is by using this regex:
string trimmed = Regex.Match(input,#"^.{1,180}\b").Value;
The only problem with that one is that it could contain trailing whitespace. To fix that, we can add a little negative look-behind:
string trimmed = Regex.Match(input,#"^.{1,180}\b(?<!\s)").Value;
That should do the trick.
How about looking at char 180, and move backwards to find the first char in (lets say space, comma, exclamation etc) indicating the start of the previous word?
Conceptially
Check that the string is over 180 characters long.
Grab the first 180 characters as a substring.
Return what you need by using the "LastIndexOf" method to get the length of the string combined with a substring to return the appropriate string.
In Code:
string InString;
InString = "Your long string goes here";
if (InString.Length>180) //Check the string length
{
InString = InString.Substring(0, 180); //Get the first 180 chars
InString = InString.Substring(0,InString.LastIndexOf(" ")); //Stop at the last space
}
This should return the correct string; though LastIndexOfAny will allow you ta add other characters to your EOL list.
You just use the normal commands on string class:
string short = myStr.Substring(0, 180);
int end = short.LastIndexOfAny(new char[] {' ', '\t', '\n'}); //maybe more
return short.Substring(0, end);