Extending a string on c# - c#

I learn c# and I have a question about strings. There is a string with full of '1's and '0's. But I don't know its length. I get the length of string with while loop. But if length is less than 8, I need to complete its length to 8 with '0's. I tried to declare a new string with 7 '0's. And did this: (where a is my string and zeroAdd is the '0's I want to add.
if(length<8)
{
for(i=length;i<8;i++)
a[i]=zeroAdd[8-length];
a[i]='\0';
}
but it didn't work. I can't use the shortcuts I saw on the internet and wanted to ask you. I would appreciate if you could explain it to me like this. Thanks in advance. Have a good one.

Why not use the inbuilt padding?
string myString = "1101";
var result = myString.PadLeft(8,'0');
Gives you:
00001101
To do it with a loop (and right-padding), you can do this:
string myString = "1101";
while (myString.Length < 8)
myString += "0";

Related

Using substring and indexOf together

I have a string like this. I need to take after first 8 character until first comma. I tried many things but i can't figure it out? Could someone help? String comes like this.
"asTyped:fTestManager.Jobs.TestReplications.TestDataReplicationsJob,Version=1.0.0.0,"
I need convert this string to
"TestManager.Jobs.TestReplications.TestDataReplicationsJob"
I've tried
string tmp= "asTyped:fTestManager.Jobs.TestReplications.TestDataReplicationsJob,Version=1.0.0.0,";
int tmpLength = tmp.Substring(9).Length;
string test = tmp.Substring(tmp.IndexOf(',') - tmpLength)
I don't know im trying somethings like this but i can't make it out. Thank you all.
Since we know the initial text is always the same 9 characters, we can simplify things somewhat:
string tmp= "asTyped:fTestManager.Jobs.TestReplications.TestDataReplicationsJob,Version=1.0.0.0,";
int startPos = 9;
int comma = tmp.IndexOf(',', startPos);
string test = tmp.Substring(startPos, comma-startPos);
string str = "asTyped:fTestManager.Jobs.TestReplications.TestDataReplicationsJob,Version=1.0.0.0,";
string result = str.Split(',')[0].Substring(9);
First we split our string with , character with the Split(char separator) method. Then we get from index 9 to the end using Substring(int startIndex).

String concatenation using String interpolation

I've something like below.
var amount = "$1,000.99";
var formattedamount = string.Format("{0}{1}{0}", "\"", amount);
How can I achieve same using String interpolation?
I tried like below
var formattedamount1 = $"\"{amount}\"";
Is there any better way of doing this using string interpolation?
Update
Is there any better way of doing this using string interpolation
No, this is just string interpolation, you cant make the following any shorter and more readable really
var formattedamount1 = $"\"{amount}\"";
Original answer
$ - string interpolation (C# Reference)
To include a brace, "{" or "}", in the text produced by an
interpolated string, use two braces, "{{" or "}}". For more
information, see Escaping Braces.
Quotes are just escaped as normal
Example
string name = "Horace";
int age = 34;
Console.WriteLine($"He asked, \"Is your name {name}?\", but didn't wait for a reply :-{{");
Console.WriteLine($"{name} is {age} year{(age == 1 ? "" : "s")} old.");
Output
He asked, "Is your name Horace?", but didn't wait for a reply :-{
Horace is 34 years old.
Same thing you can achieve by doing:
var formattedamount1 = $"\"{amount}\"";
OR
var formattedamount1 = $#"""{amount}""";
It's basically allowing you to write string.Format(), but instead of using one string with "placeholders"({0}, {1}, .. {N}), you are directly writing/using your variable inside string.
Please read more about String Interpolation (DotNetPerls), $ - string interpolation to fully understand whats going on.
Just to give one more option, if you want to make sure you use the same quote at both the start and the end, you could use a separate variable for that:
string quote = "\"";
string amount = "$1,000.99";
string formattedAmount = $"{quote}{amount}{quote}";
I'm not sure I'd bother with that personally, but it's another option to consider.

how to get text after a certain comma on C#?

Ok guys so I've got this issue that is driving me nuts, lets say that I've got a string like this "aaa,bbb,ccc,ddd,eee,fff,ggg" (with out the double quotes) and all that I want to get is a sub-string from it, something like "ddd,eee,fff,ggg".
I also have to say that there's a lot of information and not all the strings look the same so i kind off need something generic.
thank you!
One way using split with a limit;
string str = "aaa,bbb,ccc,ddd,eee,fff,ggg";
int skip = 3;
string result = str.Split(new[] { ',' }, skip + 1)[skip];
// = "ddd,eee,fff,ggg"
I would use stringToSplit.Split(',')
Update:
var startComma = 3;
var value = string.Join(",", stringToSplit.Split(',').Where((token, index) => index > startComma));
Not really sure if all things between the commas are 3 length. If they are I would use choice 2. If they are all different, choice 1. A third choice would be choice 2 but implement .IndexOf(",") several times.
Two choices:
string yourString="aaa,bbb,ccc,ddd,eee,fff,ggg";
string[] partsOfString=yourString.Split(','); //Gives you an array were partsOfString[0] is "aaa" and partsOfString[1] is "bbb"
string trimmed=partsOfString[3]+","+partsOfString[4]+","+partsOfString[5]+","+partsOfSting[6];
OR
//Prints "ddd,eee,fff,ggg"
string trimmed=yourString.Substring(12,14) //Gets the 12th character of your string and goes 14 more characters.

Search for a sub-string within a string

I am really a beginner, I already know
string.indexOf("");
Can search for a whole word, but when I tried to search for e.g: ig out of pig, it doesn't work.
I have a similar string here(part of):
<Special!>The moon is crashing to the Earth!</Special!>
Because I have a lot of these in my file and I just cannot edited all of them and add a space like:
< Special! > The moon is crashing to the Earth! </ Special! >
I need to get the sub-string of Special! and The moon is crashing to the Earth!
What is the simple way to search for a part of a word without adding plugins like HTMLAgilityPack?
IndexOf will work, you are probably just using it improperly.
If your string is in a variable call mystring you would say mystring.IndexOf and then pass in the string you are looking for.
string mystring = "somestring";
int position = mystring.IndexOf("st");
How are you using it? You should use like this:
string test = "pig";
int result = test.IndexOf("ig");
// result = 1
If you want to make it case insensitive use
string test = "PIG";
int result = test.IndexOf("ig", StringComparison.InvariantCultureIgnoreCase);
// result = 1
String.IndexOf Method - MSDN
Please try this:
string s = "<Special!>The moon is crashing to the Earth!</Special!>";
int whereMyStringStarts = s.IndexOf("moon is crashing");
IndexOf should work with spaces too, but maybe you have new line or tab characters, not spaces?
Sometimes case-sensitivity is important. You may control it by additional parameter called comparisonType. Example:
int whereMyStringStarts = s.IndexOf("Special", StringComparison.OrdinalIgnoreCase);
More information about IndexOf: String.IndexOf Method at MSDN
Anyway, I think you may need regular expressions to create better parser. IndexOf is very primitive method and you may stuck in big mess of code.
string page = "<Special!>The moon is crashing to the Earth!</Special!>";
if (page.Contains("</Special!>"))
{
pos = page.IndexOf("<Special!>");
propertyAddress = page.Substring(10, page.IndexOf("</Special!>")-11);
//i used 10 because <special!> is 10 chars, i used 11 because </special!> is 11
}
This will give you "the moon is crashing to the earth!"

Right-align a currency string (with no symbol)?

I currently output a currency value left-aligned, using the following:
String.Format(CultureInfo.CurrentCulture, "{0:#,##0}", value);
I wish to modify the string formatter so that I can right align this. Im not sure how to do it without affecting my existing formatter.
Could someone please advise?
EDIT: I Know it involves something similar to:
http://www.csharp-examples.net/align-string-with-spaces/
String.Format("{0,20:#,##0}", value); will do it.
Example.
not very clear what you actually mean, but I suppose, you are talking about
String.PadLeft method.
Example: to "align" right, you can:
string hello ="hello";
int supportedSymbCount = 10;
int padcount = supportedSymbCount - hello.Length;
if(padCount>0)
hello = hello.PadLeft(padCount);
This will add "pads" in front of the string as much as need to compose a string as long as 10 characters. Choose parameters more sutable to you, and it should work in your case.
For console output use the tab character as a separator,
Console.WriteLine( "\t{0:#,##0}", value )
For web use div class="numeric" with text-align="right".
For other outputs there are no generic solutions.
Use PadLeft or PadRight
int iTotalLength = 20; // Total length of string
char cPadChar = '0'; // Padding character
String.Format(CultureInfo.CurrentCulture, "{0:#,##0}", value).PadLeft(iTotalLength,
cPadChar);

Categories

Resources