string[] management - c#
ok, so ill cut to the chase here. and to be clear, im looking for code examples where possible.
so, i have a normal string, lets say,
string mystring = "this is my string i want to use";
ok, now that i have my string, i split it by the space with
string[] splitArray = mystring.Split(new char[] { ' ' });
ok, so now i have splitArray[0] through splitArray[7].
now, i need to do some fancy things with the string that i normally wouldnt need to do.
here are a few:
i need to cut off the first word, so i am left with the other 7 words, so that i have something like:
string myfirstword = "this";
mystring = "is my string i want to use";
now, i will need to use mystring over and over again, using different parts of it at different times, and depending on the string i will have no idea how long, it will be. so i will give some examples of things ill need.
first, ill need to know, how many words are there (this is easy, just throwing it in)
second, ill need some way of using things like,
string secondword = splitArray[1];
string everythingAfterTheSecondWord = splitArray[2+];
if you noticed, i included a [2+] ... the + indicating that i want all strings in the array put back together, spaces in all, into a string. so for example,
string examplestring = "this is my example for my stack overflow question";
string[] splitArray2 = examplestring.Split(new char[] { ' ' });
now, if i called on splitArray2[4+] i would want a return of "for my stack overflow question". now obviously its not as simple as adding a + to a string array.. but thats what i need, and under the current situation i have tried many other easier ways that simply to not work.
ALSO, if i called on something like splitArray2[2-5] i would want, words 2 through 5 obviously.
Summary:
i need greater management of my string[] arrays, and i need to be able to find, every word after word *, need to be able to strip out random words in the string while leaving the rest of the string intact, and need to be able to find string m through n
Thanks!
Most of what you're looking for can be achieved with a List<string>. Briefly:
string mystring = "this is my string i want to use";
List<string> splitArray = new List<string>(mystring.Split(new char[] { ' ' }));
string firstWord = splitArray[0];
// mystring2 = "is my string i want to use"
splitArray.RemoveAt(0);
string mystring2 = String.Join(" ", splitArray.ToArray());
To do the more complicated things you describe with splitArray[2+] requires LINQ though, and hence .NET 3.5.
List<string> everythingAfterTheSecondWord = splitArray.Skip(2).ToList();
For splitArray[2-5]:
List<string> arraySlice = splitArray.Skip(2).Take(3).ToList();
Well, to do the "every word starting at word X" you could do this:
string newString = string.join(splitArray," ",x);
To get y words starting at x, do this:
string newString = string.join(splitArray," ",x,y);
To get the number of words:
int wordCount= splitArray.Length;
Putting it all together, words x-y goes like this:
string newString = string.join(splitArray," ",x, splitArray.Length-x+1);
Related
Can I shorten this code with a loop in C#?
I have this code written in C# but looks kind of "bad" and I would like to shorten it somehow and keep it clean and simple. All this code works pretty fine but I want to know if there's any other way I can achieve the same thing. EDIT: I forgot to mention that the firstLine has a bad date format attached with it, so it is like this: "This_is_my_first_line_20220126". So I split the string and then only join it with the corrected date. The problem is that I can never know how long the new string would be and I don't want to handle the code like this and go up to 100 parts. Here's my code: string correctDate = "26012022"; string[] lines = File.ReadAllLines("text.txt"); string firstLine = lines.FirstOrDefault(); //note: firstLine looks like this: This_is_my_first_line_20220126 string[] sub = firstLine.Split('_'); string name=""; if(sub.Length==2) name = sub[0]+"_"+sub[1]+"_"+correctDate; else if(sub.Length==3) name = sub[0]+"_"+sub[1]+"_"+sub[2]+"_"correctDate; ... else if(sub.Length==20) name = sub[0]+"_"+ ... "_" + sub[19]; Now, my final name value should be "This_is_my_line_26012022" but I want it to depend on the length of the given string. So far I know that the maximum length would go up to 20 but I don't want my code to look like this. Can I shorten it somehow?
you can find the LastIndexOf the underscore and drop the date by using Substring: string firstLine = "This_is_my_first_line_20220126"; string correctDate = "26012022"; string correctString = firstLine.Substring(0, firstLine.LastIndexOf("_") + 1) + correctDate;
Still a little perplexed with the split aproach, but this a way to join back all elements string name = string.Join("_", sub.Take(sub.Length - 1).Append(correctDate)); Or use the substring method (and no need of all that split & join) name = firstLine.Substring(0, firstLine.LastIndexOf("_") +1) + correctDate;
I forgot to mention that firstLine has a bad date format like "This_is_my_Line_20220125" If you want to correct just the first line: string correctDate = "26012022"; string[] lines = File.ReadAllLines("text.txt"); lines[0] = lines[0][..^8] + correctDate; [..^8] uses C# 9's "indices and ranges" feature, that allows for a more compact way of taking a substring. It means "from the start of the string, up to the index 8 back from the end of the string". If you get a wiggly line and possibly a messages like "... is not available in C# version X" you can use the older syntax, which would be more like lines[0] = lines[0].Remove(lines[0].Length - 8) + correctDate; If you want to correct all lines: string correctDate = "26012022"; string[] lines = File.ReadAllLines("text.txt"); for(int x = 0; x < lines.Length; x++) lines[x] = lines[x][..^8] + correctDate; If the incorrect date isn't always 8 characters long, you can use LastIndexOf('_') to locate the last _, and snip it to that point
How can i analise millions of strings that merge into each other?
I have millions of strings, around 8GB worth of HEX; each string is 3.2kb in length. Each of these strings contains multiple parts of data I need to extract. This is an example of one such string: GPGGA,104644.091,,,,,0,0,,,M,,M,,*43$GPVTG,0.00,T,,M,0.00,N,0.00,K,N*32Header Test.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ$GPGGA,104645.091,,,,,0,0,,,M,,M,,*42$GPVTG,0.00,T,,M,0.00,N,0.00,K,N*32Header Test.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ ÿÿ!ÿÿ"ÿÿ#ÿÿ$ÿÿ%ÿÿ&ÿÿ'ÿÿ(ÿÿ)ÿÿ*ÿÿ+ÿÿ,ÿÿ-ÿÿ.ÿÿ/ÿÿ0ÿÿ1ÿÿ$GPGGA,104646.091,,,,,0,0,,,M,,M,,*41$GPVTG,0.00,T,,M,0.00,N,0.00,K,N*32Header Test2ÿÿ3ÿÿ4ÿÿ5ÿÿ6ÿÿ7ÿÿ8ÿÿ9ÿÿ:ÿÿ;ÿÿ<ÿÿ=ÿÿ>ÿÿ?ÿÿ#ÿÿAÿÿBÿÿCÿÿDÿÿEÿÿFÿÿGÿÿHÿÿIÿÿJÿÿ$GPGGA,104647.091,,,,,0,0,,,M,,M,,*40$GPVTG,0.00,T,,M,0.00,N,0.00,K,N*32Header TestKÿÿLÿÿMÿÿNÿÿOÿÿPÿÿQÿÿRÿÿSÿÿTÿÿUÿÿVÿÿWÿÿXÿÿYÿÿZÿÿ[ÿÿ\ÿÿ]ÿÿ^ÿÿ_ÿÿ`ÿÿaÿÿbÿÿcÿÿ$GPGGA,104648.091,,,,,0,0,,,M,,M,,*4F$GPVTG,0.00,T,,M,0.00,N,0.00,K,N*32Header Testdÿÿeÿÿfÿÿgÿÿhÿÿiÿÿjÿÿkÿÿlÿÿmÿÿnÿÿoÿÿpÿÿqÿÿrÿÿsÿÿtÿÿuÿÿvÿÿwÿÿxÿÿyÿÿzÿÿ{ÿÿ|ÿÿ$GPGGA,104649.091,,,,,0,0,,,M,,M,,*4E$GPVTG,0.00,T,,M,0.00,N,0.00,K,N*32Header Test}ÿÿ~ÿÿ.ÿÿ€ÿÿ.ÿÿ‚ÿÿƒÿÿ„ÿÿ…ÿÿ†ÿÿ‡ÿÿˆÿÿ‰ÿÿŠÿÿ‹ÿÿŒÿÿ.ÿÿŽÿÿ.ÿÿ.ÿÿ‘ÿÿ’ÿÿ“ÿÿ”ÿÿ•ÿÿ$GPGGA,104650.091,,,,,0,0,,,M,,M,,*46$GPVTG,0.00,T,,M,0.00,N,0.00,K,N*32Head as you can see it is pretty much this repeated: GPGGA,104644.091,,,,,0,0,,,M,,M,,*43$GPVTG,0.00,T,,M,0.00,N,0.00,K,N*32Header Test.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ$GPGGA,104645.091,,,,,0,0,,,M,,M,,*42$GPVTG,0.00,T,,M,0.00,N,0.00,K,N*32Header Test.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ ÿÿ!ÿÿ"ÿÿ#ÿÿ$ÿÿ%ÿÿ&ÿÿ'ÿÿ(ÿÿ)ÿÿ*ÿÿ+ÿÿ,ÿÿ-ÿÿ.ÿÿ/ÿÿ0ÿÿ1ÿÿ I want to separate this string into two lists like this: _GPSList $GPGGA,104644.091,,,,,0,0,,,M,,M,,*43 $GPVTG,0.00,T,,M,0.00,N,0.00,K,N* $GPVTG,0.00,T,,M,0.00,N,0.00,K,N _WavList 32HeaderTest.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ 32HeaderTest.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ.ÿÿ ÿÿ!ÿÿ"ÿÿ#ÿÿ$ÿÿ%ÿÿ&ÿÿ'ÿÿ(ÿÿ)ÿÿ*ÿÿ+ÿÿ,ÿÿ-ÿÿ.ÿÿ/ÿÿ0ÿÿ1ÿÿ Issue 1: This repetition isn't containing within a single string, it overflows into the next string. so if some data crosses the end and start of two strings how to I deal with that? Issue 2: How do I analyse the string and extract only the parts I need?
The solution I'm providing is not a complete answer but more like an idea which might help you get what you want. Everything else which I present is an assumption on my behalf. //Assuming your data is stored in a file "yourdatafile" //Splitting all the text on "$" assuming this will separate GPSData string[] splittedstring = File.ReadAllText("yourdatafile").Split('$'); //I found an extra string lingering in the sample you provided //because I splitted on "$", so you gotta take that into account var GPSList = new List<string>(); var WAVList = new List<string>(); foreach (var str in splittedstring) { //So if the string contains "Header" we would want to separate it from GPS data if (str.Contains("Header")) { string temp = str.Remove(str.IndexOf("Header")); int indexOfAsterisk = temp.LastIndexOf("*"); string stringBeforeAsterisk = str.Substring(0, indexOfAsterisk + 1); string stringAfterAsterisk = str.Replace(stringBeforeAsterisk, ""); WAVList.Add(stringAfterAsterisk); GPSList.Add("$" + stringBeforeAsterisk); } else GPSList.Add("$" + str); } This provides the exact output as you need, only exception is with that extra string. Also some non-standard characters might look like black blocks.
C# - Merging strings from a certain position
I want to create a function but I don't know how it would work or how to create it. I want to create a function something similar to below. I have a string, lets say its this for example: string myString = "This is my string and it will forever be my string."; What if I wanted to split this by a space and get each part? which I do... string[] parts = myString.Split(' '); Now, I want to get everything but the first 3 words in my string parts, how would I merge each string in parts except the first 3? which will return string and it will forever be my string. Something similar to this: public string getMergedString(string[] parts, int start) // This method would return everything from where you told it to start... { }
public string getMergedString(string[] parts, int start) // This method would return everything from where you told it to start... { return String.Join(" ", parts.Skip(start)); } Quick explanation of the code: string.Join(separator, IEnumerable values) This joins an IEnumerable object containing strings to one, unified string. Docs: https://msdn.microsoft.com/en-us/library/system.string.join(v=vs.110).aspx parts.Skip(int count) This part of the code skips a given amount of elements, before returning them. Skip(int count) is an extension method found in the System.Linq namespace. You need .Net 3.5 or higher in order for you to be able to use this method. Docs: https://msdn.microsoft.com/en-us/library/bb358985(v=vs.110).aspx
string myString = "This is my string and it will forever be my string."; string[] words = myString.Split(' '); var myNewString = string.Join(" ", words.Skip(3));
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.
Loop Problem: Assign data to different strings when in a loop
I have a string which consists of different fields. So what I want to do is get the different text and assign each of them into a field. ex: Hello Allan IBM so what I want to do is: put these three words in different strings like string Greeting = "Hello" string Name = "Allan" string Company = "IBM" //all of it happening in a loop. string data = "Hello Allan IBM" string s = data[i].ToString(); string[] words = s.Split(','); foreach (string word in words) { Console.WriteLine(word); } any suggestions? thanks hope to hear from you soon
If I understand correctly you have a string with place-holders and you want to put different string in those place-holders: var format="{0}, {1} {2}. How are you?"; //string Greeting = "Hello" //string Name = "Allan" //string Company = "IBM" //all of it happening in a loop. string data = ...; //I think you have an array of strings separated by , foreach( va s in data){ { //string s = data[i];//.ToString(); - it is already a string array string[] words = data[i].Split(','); Console.WriteLine(format, words[0], words[1], words[2]); }
To me it sound not like a problem that can be solved with a loop. The essential problem is that the loop can only work if you do exactly the same operation on the items within the loop. If your problem doesn't fit, you end up with a dozen of lines of code within the loop to handle special cases, what could have been written in a shorter way without a loop. If there are only two or three strings you have to set (what should be the case if you have named variables), assign them from the indexes of the split string. An alternative would be using regular expressions to match some patterns to make it more robust, if one of the expected strings is missing. Another possibility would be to set attributes on members or properties like: [MyParseAttribute(/*position*/ /*regex*/)] string Greeting {get;set;} And use reflexion to populate them. Here you could create a loop on all properties having that attribute, as it sounds to me that you are eager to create a loop :-)