Remove part of String inside List<string> - c#

I have a List<string> that will have an item in it like 2014-11-03 23:58:37.6750486_0003 and I was wondering how it could strip the following items from the list:2014-11-03 and .6750486_0003, leaving only 23:58:37.
Using the following to add the item to the List:
calltimeList.Add(msg.timestamp().as_creator_time(header.tz_offset()).ToString());
Using this
Console.WriteLine(entryTime.Substring(11, 8));
Works fine since it will always start # 11 and only be 8 characters

You can use LINQ:
List<string> lst = new List<string> { "2014-11-03 23:58:37.6750486_0003" };
List<string> calltimeList = lst.Select(s => new string(s.SkipWhile(c => c != ' ').Skip(1).TakeWhile(c => c != '.').ToArray())).ToList();

Split the string into two parts, then take the first string and use this in your list.
The Split method will return the split string into an array, so you will have the correct part in the first place in the array.
var stringYouWant = msg.timestamp().as_creator_time(header.tz_offset()).ToString().Split(',')[0];

You could substring the the string value or convert to a DateTime then use and formatter to get the desired value.
string timestamp = "2014-11-03 23:58:37.6750486_0003";
int index=timestamp.IndexOf(":");
timestamp.Substring(index - 2, 8);
or
string timestamp = "2014-11-03 23:58:37.6750486_0003";
int index = timestamp.IndexOf("_");
var time = DateTime.Parse(timestamp.Substring(0, index));

you could so something like
var newList= callTimeList.Select(c=>c.Substring(11,8)).ToList();
but I think a better solution would be to store your callTimeList as a list of dates and then stringify it as needed. My initial though was to convert the string into a date and then format it
var newList = callTimeList.Select(c=> String.Format("{0:HH:mm:ss}",c)).ToList();
but I'm not familiar with the _0003 stuff, but it isn't parsable by DateTime.Parse.

A simple SubString would do.
msg.timestamp().as_creator_time(header.tz_offset()).ToString().SubString(11, 8)
However, looks like you are working with a timestamp. If you can get a hold of the DateTime , it's more readable to do something like
myDateTime.ToString("HH:mm:ss")

Related

Using linq in .net core to parse a string and turn it into a list

I have a string that gets input like say: abcde.
I then want to take that string and do the following:
Make the string uppercase
Parse the string to get each character one by one
Add a prefix to that new string (prefix is H-I)
Return a list of every new string in order.
So using abcde the resulting list should be:
// new list items being returned
H-IA
H-IB
H-IC
H-ID
H-IE
I know there should be an easy way to do this with Linq but don't quite have it yet.
In a line
var list = str.ToUpper().ToArray().Select(c => "H-1" + c).ToList();

Need to get two values out into an array from string split

I have a string that looks like this:
var result = "y-9m-10y-9m-11y-0m-02y-0m-03";
I need to make 2 lists:
one for all the y- objects(9,9,0,0)
and another for the m- objects(10,11,02,03).
How can I do this?
I have this older code from before that doesn't care about the y- objects. Now I need to get both sets.
var result = "m-10m-11m-02m-03";
var months = result.Split(new[] { "m-" }, StringSplitOptions.RemoveEmptyEntries);
Quick and dirty solution using regular expressions and LINQ:
var months = Regex.Matches(result, #"m-(\d+)").Cast<Match>().Select(m => int.Parse(m.Groups[1].Value));
var years = Regex.Matches(result, #"y-(\d+)").Cast<Match>().Select(m => int.Parse(m.Groups[1].Value));
Note that this doesn't do any error checking.
Edit: In the question you seem to use the extracted strings without converting them to int. In this case, omit the int.Parse and use m.Groups[1].Value directly.

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);

Unable to Split the string accordingly

I know this question would have been asked infinite number of times, but I'm kinda stuck.
I have a string something like
"Doc1;Doc2;Doc3;12"
it can be something like
"Doc1;Doc2;Doc3;Doc4;Doc5;56"
Its like few pieces of strings separated by semicolon, followed by a number or id.
I need to extract the number/id and the strings separately.
To be exact, I can have 2 strings: one having "Doc1;Doc2;Doc3" or "Doc1;Doc2;Doc3;Doc4" and the other having just the number/id as "12" or "34" or "45" etc.
And yeah I am using C# 3.5
I understand its a pretty easy and witty question, but this guy is stuck.
Assistance required from experts.
Regards
Anurag
string.LastIndexOf and string.Substring are the keys to what you're trying to do.
var str = "Doc1;Doc2;Doc3;12";
var ind = str.LastIndexOf(';');
var str1 = str.Substring(0, ind);
var str2 = str.Substring(ind+1);
One way:
string[] tokens = str.Split(';');
var docs = tokens.Where(s => s.StartsWith("Doc", StringComparison.OrdinalIgnoreCase));
var numbers = tokens.Where(s => s.All(Char.IsDigit));
String docs = s.Substring(0, s.LastIndexOf(';'));
String number = s.Substring(s.LastIndexOf(';') + 1);
One possible approach would be this:
var ids = new List<string>();
var nums = new List<string>();
foreach (var s in input.Split(';'))
{
int val;
if (!int.TryParse(s, out val)) { ids.Add(s); }
else { nums.Add(s); }
}
where input is something like Doc1;Doc2;Doc3;Doc4;Doc5;56. Now, ids will house all of the Doc1 like values and nums will house all of the 56 like values.
you can use StringTokenizer functionality.
http://www.c-sharpcorner.com/UploadFile/pseabury/JavaLikeStringTokenizer11232005015829AM/JavaLikeStringTokenizer.aspx
split string using ";"
StringTokenizer st = new StringTokenizer(src1,";");
collect final String. that will be your ID.
You may try one of two options: (assuming your input string is in string str;
Approach 1
Get LastIndexOf(';')
Split the string based on the index. This will give you string and int part.
Split the string part and process it
Process the int part
Approach 2
Split the string on ;
Run a for loop - for (int i = 0; i < str.length - 2; i++) - this is the string part
Process str[length - 1] separately - this is the int part
Please take this as a starting point as there could be other approaches to implement a solution for this
string actual = "Doc1;Doc2;Doc3;12";
int lstindex = actual.LastIndexOf(';');
string strvalue = actual.Substring(0, lstindex);
string id = actual.Substring(lstindex + 1);

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