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';
}
}
Related
I am a beginner in programming. And now I'm facing a task where I can't get any further. Probably it is relatively easy to solve.
This is what I want to do: I read out a .txt file and there are several lines of content.
Example what is in the .txt file:
text1,text2,text3
text1,text2,
text1,text2,text3,text4
I'm now ready to find the right line and use it. Then I want to split the line and assign each text to its own string.
I can do this if I know that this line have 4 words. But what if I don't know how many words this line have.
For example if I want to assign 5 strings but there are only 4 arrays in the column I get an error.
My program currently looks like this:
string reader = "text1,text2,text3,text4";
string[] words = reader.Split(',');
string word1 = words[0].ToString();
string word2 = words[1].ToString();
string word3 = words[2].ToString();
string word4 = words[3].ToString();
textBox1.Text = word3;
My goal is to find out how many words are in the string. And then pass each word to a separate string.
Thank you in advance
To get the length of the Array, you can easily use .Length
In your example, you just write
int arraylength = words.Length;
I don't understand, why do you want to create a new String for every value of the string-array? You can just use them in the array.
In your example you always user .ToString(), this isn't necessary because you already have a string.
An array is just multiple variables (in your example strings) which are connected to another.
I doubt if you want separated local variables like word1, word2 etc. To see why, let's
bring the idea to the point of absurdity. Imagine, that we have a small narration with 1234
words only. Do we really want to create word1, word2, ..., word1234 local variables?
So, let's stick to a single words array only:
string[] words = reader.Split(',');
Now, you can easily get array Length (i.e. number of items):
textBoxCount.Text = $"We have {words.Length} words in total";
Or get N-th word (let N be one based) from the words array:
string wordN = array.Length >= N ? array[N - 1] : "SomeDefaultValue";
In your case (3d word) it can be
// either 3d word or an empty string (when we have just two less words)
textBox1.Text = array.Length >= 3 ? array[3 - 1] : "";
Technically, you can use Linq and query the reader string:
using System.Linq;
...
// 3d word or empty string
textBox1.Text = reader.Split(',').ElementAtOrDefault(3 - 1) ?? "";
But Linq seems to be overshot here.
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.
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);
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);
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);