Copy first few strings separated by a symbol in c# - c#

I have a string consist of integer numbers followed by "|" followed by some binary data.
Example.
321654|<some binary data here>
How do i get the numbers in front of the string in the lowest resource usage possible?
i did get the index of the symbol,
string s = "321654654|llasdkjjkwerklsdmv"
int d = s.IndexOf("|");
string n = s.Substring(d + 1).Trim();//did try other trim but unsuccessful
What to do next? Tried copyto but copyto only support char[].

Assuming you only want the numbers before the pipe, you can do:
string n = s.Substring(0, d);
(Make it d + 1 if you want the pipe character to also be included.)
I might be wrong, but I think you are under the impression that the parameter to string.Substring(int) represents "length." It does not; it represents the "start-index" of the desired substring, taken up to the end of the string.

s.Substring(0,d);

You can use String.Split() here is a reference http://msdn.microsoft.com/en-us/library/ms228388%28VS.80%29.aspx
string n = (s.Split("|"))[0] //this gets you the numbers
string o = (s.Split("|"))[1] //this gets you the letters

Related

The meaning of this code about converting in C#?

i had a function containing code like this:
Random x = new Random();
int key = x.Next(0x21, 0x7B);
string nxt = Convert.ToString(key.ToString("X")) +
Convert.ToString(key.ToString("X"))
+ Convert.ToString(key.ToString("X"))
+ Convert.ToString(key.ToString("X"));
Im very new to C#, help me, thank a lot
That code is choosing a random number between 0x21 and 0x7B, converting it to a string in hex and repeating it four times in nxt.
There are better ways to create a string with a single character multiple times (for example, the string constructor that accepts a character and a count), and the Convert.ToString call is useless since int.ToString already returns a string.
The first two lines pick a random integer between 33 and 122 inclusive (the 0xs in .Next() mean those numbers are expressed in hexadecimal notation).
The key.ToString("X") part takes that random integer, converts it to hexadecimal notation, and returns it as a string.
As Blindy pointed out, the Convert.ToString() is redundant and not necessary since it is converting a string to a string.
The final "nxt" variable would consist of that new hexadecimal number (as a string) repeated four times.
Here's a couple of other ways to get that string repeated four times:
string nxt = new StringBuilder().Insert(0, key.ToString("X"), 4).ToString();
string nxt = String.Concat(Enumerable.Repeat(key, 4));
string nxt = $"{key}{key}{key}{key}";

How to replace multiple characters in a string with other multiple characters (another string) without replacing other ocurrences?

I'm making a console application for IP assignment where a user simply enters the number of networks, the number of hosts per network and the initial network IP address, and this generates the full IP assignment table.
My biggest issue right now is that say I have a string with "172.16.0.0".
I want to grab the 0 at the end, convert it to an int, add a certain number of hosts (say, 0 + 512), and if it goes over 255, I want it to instead grab the previous 0 and replace it with a 1 instead then test it again. But I'm mostly having issues with replacing the numbers in the initial string. Since strings aren't mutable, I obviously have to make a new string with the change, but I can't see how to do this.
I've so far tried finding the index where the change will be made using the string.split function and indexof and making that an int variable called datIndex. Then I change the "172.16.0.0" string to a character array, then tried swapping the character in the previously defined index, however this limits me to a single character, which wouldn't work for a number with more than one digit. Also tried using stringbuilder but the stringbuilder object seems to be a char type so I end up in the same place, can't equal the value in the index I want to change to the new number.
string test = "172.16.0.0";
int datIndex = test.IndexOf(test.Split('.')[2]);
char[] c = test.ToCharArray();
c[datIndex] = '201'; //Not possible because more than one digit
//Also tried the following
datIndex = test.IndexOf(test.Split('.')[2]);
StringBuilder sb = new StringBuilder(test);
sb[datIndex] = '201'; //Cannot implicitly convert type string to char
string temp2 = sb.ToString();
test = temp2; //Changed string
In this example, I'd like to change the penultimate "0" in the "172.16.0.0" string to a "201" (this number would be obtained by a sum of two numbers so ideally they'd both first be integers).
However with both methods I've tried, I can't fit a number bigger than one digit into that index.
This is maybe what you are looking for:
string ip = "127.16.0.0";
string ipNumbers = ip.Split('.');
int a = int.Parse (ipNumbers[0]);
int b = int.Parse (ipNumbers[1]);
int c = int.Parse (ipNumbers[2]);
int d = int.Parse (ipNumbers[3]);
//now you have in a,b,c and d all the ip numbers, do the math with them and then do this:
ip = $"{a}.{b}.{c}.{d}";

Parse string and return only the information between bracket symbols. C# Winforms

I would like to parse a string to return only a value that is in between bracket symbols, such as [10.2%]. Then I would need to strip the "%" symbol and convert the decimal to a rounded up/down integer. So, [10.2%] would end up being 10. And, [11.8%] would end up being 12.
Hopefully I have provided sufficient information.
Math.Round(
double.Parse(
"[11.8%]".Split(new [] {"[", "]", "%"},
StringSplitOptions.RemoveEmptyEntries)[0]))
Why not use Regex?
In this example, I am assuming that your value inside the brackets always are a double with decimals.
string WithBrackets = "[11.8%]";
string AsDouble = Regex.Match(WithBrackets, "\d{1,9}\.\d{1,9}").value;
int Out = Math.Round(Convert.ToDouble(AsDouble.replace(".", ","));
var s = "[10.2%]";
var numberString = s.Split(new char[] {'[',']','%'},StringSplitOptions.RemoveEmptyEntries).First();
var number = Math.Round(Covnert.ToDouble(numberString));
If you can ensure that the content between the brackets is of the form <decimal>%, then this little function will return the value between the fist set of brackets. If there are more than one values you need to extract then you will need to modify it somewhat.
public decimal getProp(string str)
{
int obIndex = str.IndexOf("["); // get the index of the open bracket
int cbIndex = str.IndexOf("]"); // get the index of the close bracket
decimal d = decimal.Parse(str.Substring(obIndex + 1, cbIndex - obIndex - 2)); // this extracts the numerical part and converts it to a decimal (assumes a % before the ])
return Math.Round(d); // return the number rounded to the nearest integer
}
For example getProp("I like cookies [66.7%]") gives the Decimal number 67
Use regular expressions (Regex) to find the required words within one bracket.
This is the code you need:
Use an foreach loop to remove the % and convert to int.
List<int> myValues = new List<int>();
foreach(string s in Regex.Match(MYTEXT, #"\[(?<tag>[^\]]*)\]")){
s = s.TrimEnd('%');
myValues.Add(Math.Round(Convert.ToDouble(s)));
}

Remove last characters from a string in C#. An elegant way?

I have a numeric string like this 2223,00. I would like to transform it to 2223. This is: without the information after the ",". Assume that there will be only two decimals after the ",".
I did:
str = str.Remove(str.Length - 3, 3);
Is there a more elegant solution? Maybe using another function? -I donĀ“t like putting explicit numbers-
You can actually just use the Remove overload that takes one parameter:
str = str.Remove(str.Length - 3);
However, if you're trying to avoid hard coding the length, you can use:
str = str.Remove(str.IndexOf(','));
Perhaps this:
str = str.Split(",").First();
This will return to you a string excluding everything after the comma
str = str.Substring(0, str.IndexOf(','));
Of course, this assumes your string actually has a comma with decimals. The above code will fail if it doesn't. You'd want to do more checks:
commaPos = str.IndexOf(',');
if(commaPos != -1)
str = str.Substring(0, commaPos)
I'm assuming you're working with a string to begin with. Ideally, if you're working with a number to begin with, like a float or double, you could just cast it to an int, then do myInt.ToString() like:
myInt = (int)double.Parse(myString)
This parses the double using the current culture (here in the US, we use . for decimal points). However, this again assumes that your input string is can be parsed.
String.Format("{0:0}", 123.4567); // "123"
If your initial value is a decimal into a string, you will need to convert
String.Format("{0:0}", double.Parse("3.5", CultureInfo.InvariantCulture)) //3.5
In this example, I choose Invariant culture but you could use the one you want.
I prefer using the Formatting function because you never know if the decimal may contain 2 or 3 leading number in the future.
Edit: You can also use Truncate to remove all after the , or .
Console.WriteLine(Decimal.Truncate(Convert.ToDecimal("3,5")));
Use:
public static class StringExtensions
{
/// <summary>
/// Cut End. "12".SubstringFromEnd(1) -> "1"
/// </summary>
public static string SubstringFromEnd(this string value, int startindex)
{
if (string.IsNullOrEmpty(value)) return value;
return value.Substring(0, value.Length - startindex);
}
}
I prefer an extension method here for two reasons:
I can chain it with Substring.
Example: f1.Substring(directorypathLength).SubstringFromEnd(1)
Speed.
You could use LastIndexOf and Substring combined to get all characters to the left of the last index of the comma within the sting.
string var = var.Substring(0, var.LastIndexOf(','));
You can use TrimEnd. It's efficient as well and looks clean.
"Name,".TrimEnd(',');
Try the following. It worked for me:
str = str.Split(',').Last();
Since C# 8.0 it has been possible to do this with a range operator.
string textValue = "2223,00";
textValue = textValue[0..^3];
Console.WriteLine(textValue);
This would output the string 2223.
The 0 says that it should start from the zeroth position in the string
The .. says that it should take the range between the operands on either side
The ^ says that it should take the operand relative to the end of the sequence
The 3 says that it should end from the third position in the string
Use lastIndexOf. Like:
string var = var.lastIndexOf(',');

Thousand separated value to integer

I want to convert a thousand separated value to integer but am getting one exception.
double d = Convert.ToDouble("100,100,100");
is working fine and getting d=100100100
int n = Convert.ToInt32("100,100,100");
is getting one format exception
Input string was not in a correct format
Why?
try this:
int i = Int32.Parse("100,100,100", NumberStyles.AllowThousands);
Note that the Parse method will throw an exception on an invalid string, so you might also want to check out the TryParse method as well:
string s = ...;
int i;
if (Int32.TryParse(s, NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out i))
{
// if you are here, you were able to parse the string
}
What Convert.ToInt32 is actually calling in your example is Int32.Parse.
The Int32.parse(string) method only allows three types of input: white space, a sign, and digits. In the following configuration [ws][sign]digits[ws] (in brackets are optional).
Since your's contained commas, it threw an exception.
Because you're supposed to specify a string containing a plain integer number (maybe preceded by +/- sign), with no thousands separator. You have to replace the separator befor passing the string to the ToInt32 routine.
You can't have separators, just numbers 0 thru 9, and an optional sign.
http://msdn.microsoft.com/en-us/library/sf1aw27b.aspx

Categories