How to split a string if it contains period (.)? - c#

I am taking numerical input from a text box. I want to check
if(textBox1.Text.Contains("."))
like 55.37
then split the string in two parts/strings.
First part before period (55)
Second part after the period (37)

Use this:
string[] ret = textBox1.Text.Split('.');
Then you can do
if (ret.Length != 2) // error ?!?
ret[0] is integer part
ret[1] is fractional part

var splitted = textBox1.Text.Split('.');
The result will be an array of strings. In your sample, the array will have 2 strings, 55 and 37.

use string.Split method
string[] a = textBox1.Text.Split('.');
string b = a[0];
string c = a[1];

In case there is a chance your code will be executed on OS with non-windows localization please use:
var separators = new[] {CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator};
var parts = textBox1.Text.Split(separators, StringSplitOptions.None);
It looks too verbose but it may be hard to understand why your code works on your machine (with dev environment) but don't on customers.

if (!textBox1.Text.Contains('.'))
return;
var parts = textBox1.Text.Split('.')
should do the trick.

use Split method
dim s as string = textbox1.text
s.split(".")

Use the following:
textBox1.Text.Split('.')

Related

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.

MVC/C# Put a comma after every number in string

I have a string of 4 numbers:
1234
I want to convert this in the most elegant way possible in MVC to
1,2,3,4
I've tried this:
codeToSend.ToString("#,#");
but this outputs "1,234" (which I expected really).
I suspected that the following would put a comma after every digit, but to no avail.
codeToSend.ToString("#,#,#,#");
I have also tried string.format, but again I am facing the same issue.
var formattedString = string.Format("{0:0,0}", 1234);
Whats the most efficient way of doing this therefore?
Note:
The string of numbers will always be 4 digits long - and numbers only. I don't want to use Insert as this wouldn't be very elegant IMO and I am aware this question has been asked before in similar ways but it is always slightly different in crucial ways (such as formatting to thousands, not every digit or just not elegantly!).
How about just using string.Join?
int i = 1234;
string.Join(",", i.ToString().ToCharArray()); // 1,2,3,4
If 1234 is string, just use;
string s = "1234";
string.Join(",", s.ToCharArray()); // 1,2,3,4
or
string s = "1234";
string.Join(",", s.ToList()); // 1,2,3,4
This one could be more efficient. (But hardly elegant)
var target = "1234";
var result = Regex.Replace(target , #"(\d)(?=.)", "$1,");
Taking fixed string length into account, the same result could be acomplished without lookahead (simpler for reading, and with better efficiency)
var target = "1234";
var result = Regex.Replace(target, #"(\d)(\d)(\d)(\d)", "$1,$2,$3,$4");
Also, if you are processing many such values, you should compile regex before using.
var target = "1234";
var digitExceptLastRegex = new Regex(#"(\d)(?=.)", RegexOptions.Compiled);
var result = regex.Replace(target, "$1,");
But I haven't measured actual performance.

Get only numbers from line in file

So I have this file with a number that I want to use.
This line is as follows:
TimeAcquired=1433293042
I only want to use the number part, but not the part that explains what it is.
So the output is:
1433293042
I just need the numbers.
Is there any way to do this?
Follow these steps:
read the complete line
split the line at the = character using string.Split()
extract second field of the string array
convert string to integer using int.Parse() or int.TryParse()
There is a very simple way to do this and that is to call Split() on the string and take the last part. Like so if you want to keep it as a string:
var myValue = theLineString.Split('=').Last();
If you need this as an integer:
int myValue = 0;
var numberPart = theLineString.Split('=').Last();
int.TryParse(numberPart, out myValue);
string setting=sr.ReadLine();
int start = setting.IndexOf('=');
setting = setting.Substring(start + 1, setting.Length - start);
A good approach to Extract Numbers Only anywhere they are found would be to:
var MyNumbers = "TimeAcquired=1433293042".Where(x=> char.IsDigit(x)).ToArray();
var NumberString = new String(MyNumbers);
This is good when the FORMAT of the string is not known. For instance you do not know how numbers have been separated from the letters.
you can do it using split() function as given below
string theLineString="your string";
string[] collection=theLineString.Split('=');
so your string gets divided in two parts,
i.e.
1) the part before "="
2) the part after "=".
so thus you can access the part by their index.
if you want to access numeric one then simply do this
string answer=collection[1];
try
string t = "TimeAcquired=1433293042";
t= t.replace("TimeAcquired=",String.empty);
After just parse.
int mrt= int.parse(t);

Python's print "0"*5 equivalent in C#

When I need to print "00000", I can use "0"*5 in python. Is there equivalent in C# without looping?
Based on your example I figure you're going to be using these strings to help zero-pad some numbers. If that's the case, it would be easier to use the String.PadLeft() method to do your padding. You could be using the similar function in python as well, rjust().
e.g.,
var str = "5";
var padded = str.PadLeft(8, '0'); // pad the string to 8 characters, filling in '0's
// padded = "00000005"
Otherwise if you need a repeated sequence of strings, you'd want to use the String.Concat() method in conjunction with the Enumerable.Repeat() method. Using the string constructor only allows repetition of a single character.
e.g.,
var chr = '0';
var repeatedChr = new String(chr, 8);
// repeatedChr = "00000000";
var str = "ha";
// var repeatedStr = new String(str, 5); // error, no equivalent
var repeated = String.Concat(Enumerable.Repeat(str, 5));
// repeated = "hahahahaha"
One of the String ctor overloads will do this for you:
string zeros = new String('0', 5);
To add to the other answers, you won't be able to use this string constructor with another string to repeat strings, such as string s = new string("O", 5);. This only works with chars.
However, you can use Enumerable.Repeat() after adding using System.Linq; to achieve the desired result with strings.
string s = string.Concat(Enumerable.Repeat("O", 5));
Use
string s = new string( '0', 5 );
Found here
Depending on your application, this may be useful too:
int n = 0;
string s = n.ToString().PadRight(5, '0');
Don't ever, ever use this: string.Join("0", new string[6]);
Why not just "00000" ?! ducks
This one only works with zero: 0.ToString("D5");

cutting from string in C#

My strings look like that: aaa/b/cc/dd/ee . I want to cut first part without a / . How can i do it? I have many strings and they don't have the same length. I tried to use Substring(), but what about / ?
I want to add 'aaa' to the first treeNode, 'b' to the second etc. I know how to add something to treeview, but i don't know how can i receive this parts.
Maybe the Split() method is what you're after?
string value = "aaa/b/cc/dd/ee";
string[] collection = value.Split('/');
Identifies the substrings in this instance that are delimited by one or more characters specified in an array, then places the substrings into a String array.
Based on your updates related to a TreeView (ASP.Net? WinForms?) you can do this:
foreach(string text in collection)
{
TreeNode node = new TreeNode(text);
myTreeView.Nodes.Add(node);
}
Use Substring and IndexOf to find the location of the first /
To get the first part:
// from memory, need to test :)
string output = String.Substring(inputString, 0, inputString.IndexOf("/"));
To just cut the first part:
// from memory, need to test :)
string output = String.Substring(inputString,
inputString.IndexOf("/"),
inputString.Length - inputString.IndexOf("/");
You would probably want to do:
string[] parts = "aaa/b/cc/dd/ee".Split(new char[] { '/' });
Sounds like this is a job for... Regular Expressions!
One way to do it is by using string.Split to split your string into an array, and then string.Join to make whatever parts of the array you want into a new string.
For example:
var parts = input.Split('/');
var processedInput = string.Join("/", parts.Skip(1));
This is a general approach. If you only need to do very specific processing, you can be more efficient with string.IndexOf, for example:
var processedInput = input.Substring(input.IndexOf('/') + 1);

Categories

Resources