I'm trying to separate the values from an asp.net textbox which ends with line breaks. For example -
959100001
959100002
Those values must be inserted into an array like {95910001, 959100002} to do further calculation.
Any advices?
I'm using C# btw.
string test = "959100001\r\n959100002\r\n";
foreach(var item in test.Split(new char []{'\r','\n'},StringSplitOptions.RemoveEmptyEntries))
Console.WriteLine(item);
Prints:
959100001
959100002
Or as suggested by Mike:
test.Split(new string[]{Environment.NewLine},StringSplitOptions.RemoveEmptyEntries))
You have to use String.split() method which split string based upon newline delimiter and return string[] array. Further you can use long.TryParse or int.TryParse method to convert string to number (int/long) type.
I had tried this in my environment. See below....
My code snippet for your question's answer is below.
string[] lines = txtline.Text.Split(new string[]{Environment.NewLine},StringSplitOptions.RemoveEmptyEntries);
It works fine.....
Not tested:
string[] lines = TextBox1.Text.Split(Environment.NewLine);
if you just want to separate them, you can simply call Split method:
string[] lines = TextBox1.Text.Split('\n', '\r');
if you also want to convert these values to integer, try this:
int[] lines = Array.ConvertAll<string, int>(TextBox1.Text.Split('\n', '\r'), Convert.ToInt32);
Related
So, I've been learning C# and I need to remove everything after the
":" character.
I've used a StreamReader to read the text file, but then I can't use the Split function, then I tried it by using an int function to import it, but then again I can't use the Split function?
What I want this to do is import a text file that's written like;
name:lastname
name2:lastname2
And so that it only shows name and name2.
I've been searching this for a couple of days but I can't seem to figure it out!
I don't know what I'm doing wrong and how to import the text file without using StreamReader or anything else.
Edit:
I'm trying to post something to a website that goes like;
example.com/q=(name without ":")
Edit 2:
StreamReader list = new StreamReader(#"list.txt");
string reader = list.ReadToEnd();
string[] split = reader.Split(":".ToCharArray());
Console.WriteLine(split);
gives output as;
System.String[]
You've got a few issues here. First, use File.ReadLines() instead of a StreamReader, its much simpler and easier:
IEnumerable<string> lines = File.ReadLines("path/to/file");
Next, your lines variable needs to be iterated so you can get to each line of the collection:
foreach (string line in lines)
{
//TODO: write split logic here
}
Then you have to split each line on the ':' character:
string[] split = line.Split(":");
Your split variable is an array of string (i.e string[]) which means you have to access a specific index of the array if you want to see its value. This is your second issue, if you pass split to Console.WriteLine() under the hood it just calls .ToString() on the object you have passed it, and with a string[] it won't automatically give you all the values, you have to write that yourself.
So if your line variable was: "name:Steve", the split variable would have two indexes and look like this:
//split[0] = "name"
//split[1] = "Steve"
I made a fiddle here that demonstrates.
I your file size small and your name:lastname in one line use:
var lines = File.ReadAllLines("filaPath");
foreach (var line in lines)
{
var array = line.Split(':');
if (array.Length > 0)
{
var name = array[0];
}
}
if name:lastname isn't in new line tell me how it's seprated
I'm stuck. (got a thinking barrier right now) :/
I need a stringarray from a string which contaions a lot of "sometext\n\t\t\t\t00:00\n\t\t\t\t05:32\n\t\t\t\t...."
There are always 8 values in this string. I want each (of these 8 ) values in the array[8].
But most importantly are the value. (the text at the beginning is unnecessary).
Would this work:
var source = "sometext\n\t\t\t\t00:00\n\t\t\t\t05:32\n\t\t\t\t...."
var result = source.Split(new []{"\n\t\t\t\t"}, StringSplitOptions.None);
that is: guessing that all your values are separated by that newline+4 tabs.
If that is not (always) the separator, then you need to specify how to identify a "value" from a "separator".
I think the following code will do what you need
int i,j;
int[] array=new int[8];
string s="sometext\n\t\t\t\t00:00\n\t\t\t\t05:32\n\t\t\t\t...."; // or input something
for(i=j=0;i<s.Length;i++){
if (s[i]>='0'&&s[i]<='9'){
array[j++]=s[i]-'0';
}
}
Well I have export to CSV script.
I export list of struct. I write with help of StringWriter. In struct field array foreach cycle I iterate through all properties and after every property I put ';'. In the end of line I put WriteLine().
So as output I have:
value1;value2;value3;
And I want:
value1;value2;value3
The question is : how to get what I want from what I get, or based on what I'v already made.
I have 3 ideas right now:
The last 2 symbols in line should be something like ";\r(\n)" So replace this combination with nothing.
Check if the property is last.
Trim last(before newline) symbol in each row.
Use String.Join to form each line for your output. It prevents you from having to check which term is last.
http://msdn.microsoft.com/en-us/library/57a79xd0.aspx
var values = { "value1", "value2", "value3" };
string line = string.Join(";", values);
line will be
"value1;value2;value3"
try this code,
str.TrimEnd(';');
Usually I just delete the last character after the line is formed.
I use a StringBuilder and just do:
var builder = new StringBuilder();
// ...
// add the text
// ...
builder.Length--;
This way I can avoid the string copy.
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('.')
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);