String interpolation: apply multiple times at once [duplicate] - c#

This question already has answers here:
Is there an easy way to return a string repeated X number of times?
(21 answers)
Closed 2 years ago.
Is there any way to interpolate variable several times without repeating?
For example:
var name = "bla";
Console.WriteLine($"foo {name:repeat:2} bar")
to print
foo blabla bar
I'm particularly interested in interpolating several line breaks instead of repeating {Environment.NewLine} several times in the interpolation mask like this:
$"{Environment.NewLine}{Environment.NewLine}"

public static string Repeat(this string s, int times, string separator = "")
{
return string.Join(separator, Enumerable.Repeat(s, times));
}
Then use:
Console.WriteLine($"foo {name.Repeat(2)} bar")

You could write an extension method for the string type, thats repeating its input. Then simply use this method within the curly braces.

You could also use
var name = "bla";
Console.WriteLine("foo {0}{0} bar", name);
// or
var s = String.Format("foo {0}{0} bar", name);
It will help you not repeating the same string, just index of it.
More about String Format

Related

Is it possible to convert Hello.World to ["Hello"]["World"]? [duplicate]

This question already has answers here:
Put result of String.Split() into ArrayList or Stack
(5 answers)
Closed 2 years ago.
I was wondering if there is a way to convert example:
'Hello.World' into '["Hello"]["World"]' or 'This.is.a.string' into ["This"]["is"]["a"]["string"]
I'm kinda new to C# and I was wondering if that's even possible using string formatting or something like that.
You can use the Split method like this string[] strings = String.Split("."); This will split your string per each period.
If you meant to include the single quotes (') as part of the string then:
String test = "'Hello.World'";
// Strip the first and last '
test = test.Substring(1, test.Length - 2);
// Split on Period
String[] split = test.Split('.');
// Encapsulate each word with [" "]
// and add back in the single quotes
var result = $"'{String.Join("", split.Select(word => $"[\"{word}\"]"))}'";
Prints:
'["Hello"]["World"]'
If they just meant to surround your input then just:
String test = "Hello.World";
// Split on Period
String[] split = test.Split('.');
// Encapsulate each word with [" "]
var result = $"{String.Join("", split.Select(word => $"[\"{word}\"]"))}";
Prints: ["Hello"]["World"]

C# add new text to string WITHOUT copy it previous value [duplicate]

This question already has answers here:
Most efficient way to concatenate strings?
(18 answers)
Closed 3 years ago.
I have string that i need to combine with another string , for example
string string1 = "cars"; // the text is just for example
string string2 = "white";
// then
string string1 = string1 + string2;
// or
string string1 += string2;
Alright , at first glance it doesn't have any problem right ?
NOPE , it does have problem
when the string.length / the string contain A LOT OF CHARACTER , for example when it contain 100.000 word , it start to get laggy or freeze when i put it inside loop, because it need to copy 100.000 word plus word from the other string everytime it combines string1 with string2 .
Is the any alternative way to add new text to string that contain massive amount of word ?
The correct way to accumulate strings in c# is using StringBuilder.
Example:
StringBuilder sb = new StringBuilder();
sb.Append("...");
sb.Append("...");
....
var result = sb.ToString()
Your solution appear to lag, since every time you "modify" a string a brand new one is created instead, so the garbage collector get a little crazy...

How to check if string contains special part [duplicate]

This question already has answers here:
How can I check if a string contains a character in C#?
(8 answers)
Closed 5 years ago.
How I can check if my string has the value ".all" in. Example:
string myString = "Hello.all";
I need to check if myString has .all in order to call other method for this string, any ideas how I can do it?
you could use myString.Contains(".all")
More info here
Use IndexOf()
var s = "Hello.all";
var a = s.IndexOf(".all", StringComparison.OrdinalIgnoreCase);
If a = -1 then no occurrences found
If a = some number other than -1 you get the index (place in the string where it starts).
So a = 5 in this case
Simply call .Contains(".all") on the string object:
if (myString.Contains(".all")
{
// your code to call the other method goes here
}
There is no need for regex to do that.
Optionally, as mentioned by #ZarX in comments, you can check if the string ends with your keyword with .EndsWith(".all"), which will return true if the string ends with your keyword.

How to check if string contains C# string.Format placeholder [duplicate]

This question already has an answer here:
Learning Regular Expressions [closed]
(1 answer)
Closed 6 years ago.
How can I simply check if a string contains {x} (x can be any number)?
I guess there is some simple RegEx to do this.
"This string contains {0} a placeholder".HasPlaceholder == true
and
"This string contains no placeholder".HasPlaceholder == false
You can write a simple extension and use a regex:
public static class StringExtensions
{
public static bool HasPlaceholder(this string s)
{
return Regex.IsMatch(s, "{\\d+}");
}
}
This regex works only for the placeholders you specified (containing only a number).
For a full placeholder you would need something like "{\\d+(,-?\\d+)?(:[A-Z]\\d*)?}". But this still needs refinement. See "Standard Numeric Format Strings" for a full list of valid symbols.
You can use this extension like this:
string s = "This string contains {0} a placeholder";
if (s.HasPlaceholder())
Console.WriteLine("Contains placeholders");

Capitalizing the first letter of a string only [duplicate]

This question already has answers here:
Make first letter of a string upper case (with maximum performance)
(42 answers)
Closed 7 years ago.
I have already taken a look at such posts like:
Format to first letter uppercase
How to capitalise the first letter of every word in a string
But none of these seem to actually work. I would have thought to start with that there would just be a:
.Capitalize();
Like there is:
.Lower(); & .Upper();
Are there any documentation or references regarding converting to a string like the following?
string before = "INVOICE";
To then becoming:
string after = "Invoice";
I receive no errors using the way the posts solutions I read give me, however, the before still remains capitalized.
What about using ToUpper on the first char and ToLower on the remaining string?
string after = char.ToUpper(before.First()) + before.Substring(1).ToLower();
You can create a method that does something like this:
string UppercaseFirst(string str)
{
if (string.IsNullOrEmpty(str))
return string.Empty;
return char.ToUpper(str[0]) + str.Substring(1).ToLower();
}
And use it like this:
string str = "thISstringLOokSHorribLE";
string upstr = UppercaseFirst(str);
to get this:
Thisstringlookshorrible

Categories

Resources