This question already has an answer here:
string.Remove doesnt work [duplicate]
(1 answer)
Closed 9 years ago.
I have such code and can't understand where is the mistake, despite the fact, that this code pretty easy. So q is a full path, and I need to get required path to Gen_ParamFile
string q = #"C:\ProgramData\RadiolocationQ\script-Data=12^6-12^33.xml";
string _directoryName1 = #"C:\ProgramData\RadiolocationQ";
int Length = _directoryName1.Length + "ascript".Length;
string Gen_ParamFile = q;
Gen_ParamFile.Remove(0, Length); // this line don't do anything
var Gen_Parfile = Path.Combine(_directoryName1, "GeneralParam-Data" + Gen_ParamFile);
I used function like said here http://msdn.microsoft.com/ru-ru/library/9ad138yc(v=vs.110).aspx
It does, it just doesn't affect the actual string, it creates a new one as a result. Use:
Gen_ParamFile = Gen_ParamFile.Remove(0, Length);
Because String.Remove method returns a new string. It doesn't change original one.
Returns a new string in which a specified number of characters in the
current instance beginning at a specified position have been deleted.
Remember, strings are immutable types. You can't change them. Even if you think you change them, you actually create new strings object.
You can assign itself like;
Gen_ParamFile = Gen_ParamFile.Remove(0, Length);
As an alternative, you can use String.SubString method like;
Gen_ParamFile = Gen_ParamFile.SubString(Length);
defiantly you can use like
Gen_ParamFile = Gen_ParamFile.Remove(0, Length);
apart from that you can also use
String.Substring method according to your requirment
Related
This question already has answers here:
How can I parse the int from a String in C#?
(4 answers)
Closed 3 months ago.
I have this line of code
bool containsInt = "Sanjay 400".Any(char.IsDigit)
What I am trying to do is extract the 400 from the string but
Any(char.IsDigit)
only returns a true value. I am very new to coding and c# especially.
As you already found out, you cannot use Any for extraction.
You would need to use the Where method:
List<char> allInts = "Sanjay 400".Where(char.IsDigit).ToList();
The result will be a list containing all integers/digits from your string.
Ok if you are interested in the value as integer you would need to convert it again to a string and then into an integer. Fortunately string has a nice constructor for this.
char[] allIntCharsArray = "Sanjay 400".Where(char.IsDigit).ToArray();
int theValue = Convert.ToInt32(new string(allIntCharsArray));
If you are using .NET 5 or higher you could also use the new cool TryParse method without extra string conversion:
int.TryParse(allIntCharsArray, out int theValue);
int result = int.Parse(string.Concat("Sanjay 400".Where(char.IsDigit)));
Use the Regex
var containsInt = Convert.ToInt32(Regex.Replace(#"Sanjay 400", #"\D", ""));
Regular expressions allow you to take only numbers and convert them into integers.
By using the C# 8 feature Range, does it create a new string in memory or does it provide a "pointer" to the memory parts of the previous string already there?
var x = "foo"[1..2];
Is compiled to;
int num = 1;
int length = 2 - num;
"foo".Substring(num, length);
And .Substring will create a new copy of the characters.
If you don't need a string, you could use "foo".AsSpan()[1..2];
I'm not following your question. A range of a string is not a string, its an array of char. string implements IEnumerable<char>.
If you want a substring, then you should use string.Substring, and yes, it will create a new string.
This question already has answers here:
Get Substring - everything before certain char
(9 answers)
Closed 8 years ago.
Lets say I have a string:
string a = "abc&dcg / foo / oiu";
now i would like the output to be
"abc&dcg"
i have tried:
string output= a.Substring(a.IndexOf('/'));
but it returns the last part not the first part
I have tried trim() as well, but doesn't provide me with the results.
Try this:
string result = a.Split('/')[0].Trim();
The split operation will give you the 3 substrings separated by '/' and you can choose whichever ones you want by specifying the index.
Try this one
string a = "abc&dcg / foo / oiu";
string output = a.Substring(0, a.IndexOf("/"));
Console.WriteLine(output);
It will show
abc&dcg
Try
string output;
if (a.IndexOf('/')>=0) { output = a.Split('/')[0].Trim() };
This wil prevents error case a doesn't contains any /
This question already has answers here:
String.Replace() vs. StringBuilder.Replace()
(9 answers)
Closed 9 years ago.
I have downloaded a stream as a byte[] 'raw' that is about 36MB. I then convert that into a string with
string temp = System.Text.Encoding.UTF8.GetString(raw)
Then I need to replace all "\n" with "\r\n" so I tried
string temp2 = temp.Replace("\n","\r\n")
but it threw an "Out of Memory" exception. I then tried to create a new string with a StringBuilder:
string temp2 = new StringBuilder(temp).Replace("\n","\r\n").toString()
and it didn't throw the exception. Why would there be a memory issue in the first place (I'm only dealing with 36MB here), but also why does StringBuilder.Replace() work when the other doesn't?
When you use:
string temp2 = temp.Replace("\n","\r\n")
for every match of "\n" in the string temp, the system creates a new string with the replacement.
With StringBuilder this doesn't happens because StringBuilder is mutable, so you can actually modify the same object without the need to create another one.
Example:
temp = "test1\ntest2\ntest3\n"
With First Method (string)
string temp2 = temp.Replace("\n","\r\n")
is equivalent to
string aux1 = "test1\r\ntest2\ntest3\n"
string aux2 = "test1\r\ntest2\r\ntest3\n"
string temp2 = "test1\r\ntest2\r\ntest3\r\n"
With Secon Method (StringBuilder)
string temp2 = new StringBuilder(temp).Replace("\n","\r\n").toString()
is equivalent to
Stringbuilder aux = "test1\ntest2\ntest3\n"
aux = "test1\r\ntest2\ntest3\n"
aux = "test1\r\ntest2\r\ntest3\n"
aux = "test1\r\ntest2\r\ntest3\r\n"
string temp2 = aux.toString()
Following StringBuilder from MSDN:
Most of the methods that modify an instance of this class return a
reference to that same instance, and you can call a method or property
on the reference. This can be convenient if you want to write a single
statement that chains successive operations.
So when you call replace with String the new object (big data - 36MB) will be allocate to create new string. But StringBuilder accessing same instance objects and does not create new one.
There is a concept of memory pressure, meaning that the more temporary objects created, the more often garbage collection runs.
So:
StringBuilder creates fewer temporary objects and adds less memory pressure.
StringBuilder Memory
Replace
We next use StringBuilder to replace characters in loops. First convert the string to a StringBuilder, and then call StringBuilder's methods. This is faster—the StringBuilder type uses character arrays internally
String is immutable in C#. If you use string.replace() method, the system will create a String object for each replacement. StringBuilder class will help you avoid object creation.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Convert.ToInt32() a string with Commas
i have a value in the label as: 12,000
and i wish to convert it into an integer like 12000 (use it for comparison)
i tried int k = convert.toint32("12,000"); this does not work.
Thanks
You're being screwed up by the comma. If all of your values have commas in them, you'll want to run a string.replace() to remove them. Once that comma is gone, it should work fine.
A more thorough way would be to Parse it, allowing for thousands.
Try the following
var number = Int32.Parse("12,000", System.Globalization.NumberStyles.AllowThousands);
Try this
string num = "12,000";
int k = Convert.ToInt32(num.Replace(",",""));
string k = "12,000";
int i = Convert.ToInt32(k.Replace(",", ""));
will work