I have the following code:
var str = "ABC";
var n = 7;
var output = String.Format("{0,n}", str);
This should output the string
" ABC"
How should I change the line above?
Format strings are just strings too - you can define the format separately:
int n = 3;
string format = string.Format("{{0,{0}}}", n);
//or more readable: string format = "{0," + n + "}";
var output = string.Format(format, str);
Edit:
After your update it looks like what you want can also be achieved by PadLeft():
var str = "ABC";
string output = str.PadLeft(7);
Just write:
var lineLength = String.Format("{0," + n + "}", str);
var s="Hello my friend";
string leftSpace = s.PadLeft(20,' '); //pad left with special character
string rightSpace = s.PadRight(20,' '); //pad right with special character
Related
str="Brand : TROLLBEADS";
int length = str.Length;
length = length - 6;
str = str.Substring(6, length);
i want to display "TROLLBEADS"
and want to discard other remaining string
You can split the string using : delimiter if it is fixed
var result = str.Split(':')[1].Trim();
or if your string can have multiple : in that case
var result = str.Substring(str.IndexOf(":") + 1).Trim();
Split is nice, but a bit too much. You can just specify the start position for substring.
string str="Brand : TROLLBEADS";
string val = str.Substring(str.IndexOf(":") + 1);
Console.WriteLine(val);
string keywords = "heard";
string strText = "Have you not heard!! what I said?"
string[] words = strText.Split(' ');
string result = "";
for (int i = 0; i < words.Length; i++)
{
if (words[i].Contains(keywords))
result += "<span>" + words[i] + "</span>" + " ";
else
result += words[i] + " ";
}
I get following output:
Have you not <span>heard!!</span> what I said?
Desired output:
Have you not <span>heard</span>!! what I said?
Can someone guide how can I get the desired output. The strText can only be split with a space.
Use String.Replace
var result = strText.Replace(keywords, "<span>" + keywords + "</span>");
If you have many keywords to replace, then just do replacement in a loop:
string[] keywords = { "heard", "said" };
string result = "Have you not heard!! what I said?";
foreach(var keyword in keywords)
result = result.Replace(keyword, "<span>" + keyword + "</span>");
Alternative solution is regular expression replacement:
string keywords = "heard|said";
string result = "Have you not heard!! what I said?";
result = Regex.Replace(result, keywords, m => "<span>" + m.Value + "</span>");
Why are you even looping through all words? This will give you the same:
string strText = "Have you not heard!! what I said?";
string newText = strText.Replace("heard", "<span>heard</span>");
From following string String1 I want to remove everything before "am" and everything after "Uhr"
string String1 = "Angebotseröffnung am 27.03.2014, 11:00 Uhr, Ort: Vergabestelle, siehe a).";
So at the end I have this string. "am 27.03.2014, 11:00 Uhr".
I am using this code but I know this is not a good approach. Can some one help me with better options.
String1 = String1.Replace("Angebotseröffnung", "");
String1 = String1.Replace("Ort", "");
String1 = String1.Replace("Vergabestelle", "");
String1 = String1.Replace("siehe", "");
String1 = String1.Replace("a)", "");
Try something like this:
var string1 = "Angebotseröffnung am 27.03.2014, 11:00 Uhr, Ort: Vergabestelle, siehe a).";
var startIndex = string1.IndexOf("am"); // 18
var endIndex = string1.IndexOf("Uhr") + 3; // 42
// Get everything between index 18 and 42
var result = string1.Substring(startIndex, endIndex - startIndex);
// result: "am 27.03.2014, 11:00 Uhr"
Another option is to use Regex.Match.
string output = Regex.Match(String1, "am.*Uhr").Value;
But it will work only if you definitely have am and Uhr in your string.
Depending on your input you may require am.*?Uhr or (?:a|p)m.*?Uhr regex.
If the format is strict and always contains Angebotseröffnung am and Uhr this is the most efficient:
string String1 = "Angebotseröffnung am 27.03.2014, 11:00 Uhr, Ort: Vergabestelle, siehe a).";
string result = null;
string startPattern = "Angebotseröffnung am ";
int start = String1.IndexOf(startPattern);
if (start >= 0)
{
start += startPattern.Length;
string endPattern = " Uhr";
int end = String1.IndexOf(endPattern, start);
if (end >= 0)
result = String1.Substring(start, end - start + endPattern.Length);
}
if you know that the format will always be the same =>
var r = new Regex("am \d{1,2}.\d{1,2}.\d{4} Uhr");
var result = r.Match(input);
With StringBuilder, Replace works the same way as with strings but it doesn't need its result to be assigned
class Program
{
static void Main()
{
const string samplestring = "hi stack Over Flow String Replace example.";
// Create new StringBuilder from string
StringBuilder str = new StringBuilder(samplestring );
// Replace the first word
// The result doesn't need assignment
str.Replace("hi", "hello");
Console.WriteLine(b);
}
}
Output Will be -->
hello stack Over Flow String Replace example
if the string will always contain am and Uhr, and will always have am before Uhr:
string String1 = "Angebotseröffnung am 27.03.2014, 11:00 Uhr, Ort: Vergabestelle, siehe a).";
int indexOfAm = String1.IndexOf("am");
int indexOfUhr = String1.IndexOf("Uhr");
string final = String1.Substring(indexOfAm, (indexOfUhr + 3) - indexOfAm);
Try this
String1 = String1.Substring(String1.IndexOf("am"), (String1.IndexOf("Uhr") - String1.IndexOf("am"))+3);
original String is "Hello World"
Output Should be "World Hello"
What is the optimized way to do it in c# ?
Please suggest me any existing link if i am missing
var s = "Hello world";
var result = String.Join(" ", s.Split(' ').Reverse()));
OR (better split below if you ar not sure of your data)
var s = "Hello world";
var result = String.Join(" ", Regex.Split(s, #"\s").Reverse());
I would split the sentence by the words (the space between them):
string[] words = helloString.Split(" ");
helloString = words[1] + " " + words[0];
You could optimise this to work with any sentence with any number of words by looping through words from the last element to the first.
I've reassigned the new string back to helloString (the original) as I assume this is what you want based on the question.
Try This Code :
string value = "Hello world";
string firstvalue = value.Split(' ').First();
string secvalue = value.Split(' ').Last();
string value = secvalue + firstvalue;
static void Main(string[] args)
{
String str = "Hello World";
String[] strNames = str.Split(' ');
for(int i=strNames.Length-1;i>=0;i--)
Console.Write(strNames[i]+" ");
}
char[] Delimiter = new char[] { ' ' }
string[] t = string.split("Hello Wordl", Delimiter)
int lenS = t.Count;
string result = "";
for(int x =t-1; t > -1; t--)
{
result += t[x] + " ";
}
//Used result now
public String GetDirectory(String Path)
{
Console.WriteLine("Directorul: ");
var start = Path.IndexOf(":") + 6;
var match2 = Path.Substring(start, Path.IndexOf(".") - start);
return Path;
}
I need to get the path string between the 2 characters in this string:
"C:\Documents\Text.txt"
I want it to show the text between ':' and '.' at the end so :"\Documents\Text"
int start_index = Path.IndexOf(':')+1;
int end_index = Path.LastIndexOf('.');
int length = end_index-start_index;
string directory = Path.Substring(start_index,length);
Linq is always fascinating:
string s = string.Join("",
Path.SkipWhile(p => p != ':')
.Skip(1)
.TakeWhile(p => p != '.')
);
You can use string operations, but you can also use the System.IO.Path functions for a - in my personal opinion - more elegant solution:
string path = #"C:\Documents\Text.txt";
string pathRoot = Path.GetPathRoot(path); // pathRoot will be "C:\", for example
string result = Path.GetDirectoryName(path).Substring(pathRoot.Length - 1) +
Path.DirectorySeparatorChar +
Path.GetFileNameWithoutExtension(path);
Console.WriteLine(result);
you should return your match2 instead of the path since path will remain C:\Documents\Text.txt
public String GetDirectory(String Path)
{
Console.WriteLine("Directorul: ");
var start = Path.IndexOf(":") + 6;
var match2 = Path.Substring(start, Path.IndexOf(".") - start);
return match2;
}
patch = patch.Substring(patch.IndexOf(':') + 1, patch.IndexOf('.') - 2);