Read string word by word with .Substring? - c#

I'v got the following String string gen = "Action;Adventure;Drama;Horror;
I tried to seperate the string word by word with .substring like: gen.Substring(gen.IndexOf(';')+1, gen.IndexOf(';'))
But my output is just "Advent".
Any help?
Background: The string collects the names of checkboxes that are checked. The string is then saved in a database.
I want to read out the string an check each checkbox on another form.

Just split it:
var parts = gen.Split(';');
(Then you can iterate over that via foreach.)

Split it like this:
public class Example
{
public static void Main()
{
String value = "Action;Adventure;Drama;Horror";
Char delimiter = ';';
String[] substrings = value.Split(delimiter);
foreach (var substring in substrings)
Console.WriteLine(substring);
}
}

Related

string.split parse url from large string

How would I parse and extract the url from this large string of text in the image below?
I want the .m3u8 link.
I tried using String.split() but that only accepts chars and not strings.
I dont know this approach would be right but I guess you can remove those lines containing "EXT" if they are common in your url.
var result = url.Split(new [] { '\r', '\n' }); // converting string to lines
for (int i=0;i<=result.Length-1;i++) // Finding if EXT text is present and removing them
{
if (result[i].Contains("EXT-")
result.RemoveAt(i);
}
string final = string.Join("", result); // converting back to string
Tell me if it works for you!
How would I parse and extract the url from this large string of text?
use this code:
void Main()
{
var text = #"
otEXT-X-MEDIA:TYPE=VIDEO,GROUP-ID=720p30',NAME=*720p°,AUTOSELECT=YES,DEFAULT=YESEXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=2374703,RESOLUTION=1280x720,CODECS=•avc1.77.31,mp4a.40.2',VIDEO=720p30'
http://video-weaver.lax03.hls.tbmw.net/v1/playlist/CuoCf3YooUjSfbk71Zs3ig68T2vDVg7449mAN78mSV1oQ9V7skuTh6NP9FOSaIgGNgnpliscdDC9XvjGyGcYrIXBbAXSkqCGuIOTQgtIw5IQLUIbHGMZIXWZeD6Urd4GzyPxCoARIYyo6i5ECCfK2r1jW1kidXGotcRXy6fHolJw-rC9xPPYc2IxYKaERQ9NsOMGn3m2ChqWFSpRHbYNK1M8OrU4WecMwgoFkORbEBEmAmng2V8GnGz63hWNV2sDW1H9E5pYjG4jpPLEf_Fwt75CePIgyZ9g30Kgr5CHZYSyMMbMAX-eac5wC3wjVUWtGz094t4xH1713yvWjv813vCY6NRBCPkCINdpXBmUnLcnE1JOLye_NiGx5R1B4IMDpRXDZQAO6PBm97ZNhyLZKc9Awg5vypphWG2MMAGdboca5WGtG_wVRp12SiHw9n0a51VpqNjVVVWbASuUly-CEe22tzLkwEolOWGE8VQSECyPx17qBU7YPHCEEi8ncnMaDly1Dn8j0xU-QN71kA.m3u8
";
MatchCollection ms = Regex.Matches(text, #"(www.+|http.+)([\s]|$)");
string url = ms[0].Value.ToString();
Console.WriteLine(url);
}
I tried using String.Split but that only accepts chars and not strings.
this question you can use extension
but it's can't deal your problem
void Main()
{
var extention_str = "http://aaacccddd".Split("ccc");
}
public static class StrinExtention {
public static string [] Split(this string str,string separator){
return str.Split(new string [] {separator},StringSplitOptions.None);
}
}

When i used String.Split the subsequent array only contains the first value? [duplicate]

This question already has answers here:
split a string on newlines in .NET
(17 answers)
Closed 6 years ago.
After reading a text file, I pass the information through a method that splits the string to get the required information for each field. I have gotten to the point where i split the string based on new lines, but it is beyond me why when I display the subsequent array (or list it's converted to), it only shows the first half of the first split string.
An example of how the input string looks:
ASSIGNMENT
In-Class Test 02/07/2014
In-Class Test 21/04/2013
Find my code below (the numLines variable was to simply see if it was being split into the correct number of lines as it should)
private void assignmentfinder(string brief, string id)
{
string searchcrit = "ASSIGNMENT";
string assignment = brief.Substring(brief.IndexOf(searchcrit) + searchcrit.Length);
string[] assignmentsplit;
assignmentsplit = assignment.Split('\t');
List<string> Assign = new List<string>(assignmentsplit);
listBox2.DataSource = Assign;
int numLines = assignment.Split('\n').Length;
richTextBox1.Lines=(assignmentsplit);
}
The output I get is:
In-Class Test
02/07/2014
Whereas it should show the second string split as well. Any ideas?
The problem is in the value of "brief" variable. Make sure the value you are putting in "brief" variable, actually conains "\n" and "\t".
You could use regex like this:
private void assignmentfinder(string brief, string id)
{
Regex rgxLines = new Regex(#"^(.*?)[ \t]+([0-9]{2}\/[0-9]{2}\/[0-9]{4})", RegexOptions.Multiline);
MatchCollection mLines = rgxLines.Matches(brief);
foreach (Match match in mLines)
{
richTextBox1.Text += String.Format("Test: {0}{1}Date: {2}{1}{1}",
match.Groups[1].Value,
Environment.NewLine,
match.Groups[2].Value);
}
}
Your mistake is that you split for each tab (\t). Split for the new line as you say:
private void assignmentfinder(string brief, string id)
{
string searchcrit = "ASSIGNMENT";
string assignment = brief.Substring(brief.IndexOf(searchcrit) + searchcrit.Length);
string[] assignmentSplit = assignment.Split('\n'); // splitting at new line
richTextBox1.Lines = assignmentSplit;
listBox2.DataSource = assignmentSplit.ToList();
}
I hope this helps.
EDIT: Just fixed a huge mistake
Question: Is it on purpose that the string id is never used?
You could use Linq to split on new line, then on tab, skipping the first line then aggregate into a list of string:
string brief = #"ASSIGNMENT
In-Class Test 02/07/2014
In-Class Test 21/04/2013";
List<string> theLines = new List<string>();
var lines = brief.Split('\n').Skip(1).Select (b => b.Split('\t'));
foreach (var line in lines)
{
for (int i = 0; i < line.Length; i++)
{
theLines.Add(line[i]);
}
}

Parse a string in C#

I've the following string that I get from a method. I would like to parse it and make pairs. The order of input string will not change.
INPUT:
ku=value1,ku=value2,ku=value3,ku=value4,ku=value5,lu=value6,lu=value7,lu=value8,lu=value9
OUTPUT
Name value1
Title value2
School value3
.
.
.
Age value9
I think I can read through the string and assign value to the left hand side as I go and so on. However, I am very new to C#.
Use string.Split and split imput string to list key-value pair then split each pair to key and value. Tahts all.
You can do something like this:
void Main()
{
string str = "ku=value1,ku=value2,ku=value3,ku=value4,ku=value5,lu=value6,lu=value7,lu=value8,lu=value9";
var tempStr = str.Split(',');
var result = new List<KeyValue>();
foreach(var val in tempStr)
{
var temp = val.Split('=');
var kv = new KeyValue();
kv.Name = temp[0];
kv.Value = temp[1];
result.Add(kv);
}
}
public class KeyValue
{
public string Name {get;set;}
public string Value{get;set;}
}
If you don't need the first part you can do this using String split as follow
Split String on , using String.Split method creating sequence of string {"ku=value1","ku=value2",...}
Use Linq's Select method to apply an additional transformation
Use Split again on each item on the '=' character
Select the item to the right of the '=', at index 1 of the newly split item
Loop through everything and print your results
Here's the code
var target = "ku=value1,ku=value2,ku=value3,ku=value4,ku=value5,lu=value6,lu=value7,lu=value8,lu=value9";
var split = target.Split(',').Select(a=>a.Split('=')[1]).ToArray();
var names = new[]{"Name","Title","School",...,"Age"};
for(int i=0;i<split.Length;i++)
{
Console.WriteLine(names[i]+"\t"+split[i]);
}
If you want to find out more about how to use these methods you can look at the MSDN documentation for them :
String.Split(char[]) Method
Enumerable.Select Method
I suggest to try this way. Split() plus regular expression
string inputString = "ku=value1,ku=value2,ku=value3,ku=value4,ku=value5,lu=value6,lu=value7,lu=value8,lu=value9";
string pattern = "(.*)=(.*)";
foreach(var pair in inputString.Split(','))
{
var match = Regex.Match(pair,pattern);
Console.WriteLine(string.Format("{0} {1}",match.Groups[1].Value, match.Groups[2].Value));
}

Extract multiple values from string using C#

I'am creating my own forum. I've got problem with quoting messages. I know how to add quoting message into text box, but i cannot figure out how to extract values from string after post. In text box i've got something like this:
[quote IdPost=8] Some quoting text [/quote]
[quote IdPost=15] Second quoting text [/quote]
Could You tell what is the easiest way to extract all "IdPost" numbers from string after posting form ?.
by using a regex
#"\[quote IdPost=(\d+)\]"
something like
Regex reg = new Regex(#"\[quote IdPost=(\d+)\]");
foreach (Match match in reg.Matches(text))
{
...
}
var originalstring = "[quote IdPost=8] Some quoting text [/quote]";
//"[quote IdPost=" and "8] Some quoting text [/quote]"
var splits = originalstring.Split('=');
if(splits.Count() == 2)
{
//"8" and "] Some quoting text [/quote]"
var splits2 = splits[1].Split(']');
int id;
if(int.TryParse(splits2[0], out id))
{
return id;
}
}
I do not know exactly what is your string, but here is a regex-free solution with Substring :
using System;
public class Program
{
public static void Main()
{
string source = "[quote IdPost=8] Some quoting text [/quote]";
Console.WriteLine(ExtractNum(source, "=", "]"));
Console.WriteLine(ExtractNum2(source, "[quote IdPost="));
}
public static string ExtractNum(string source, string start, string end)
{
int index = source.IndexOf(start) + start.Length;
return source.Substring(index, source.IndexOf(end) - index);
}
// just another solution for fun
public static string ExtractNum2(string source, string junk)
{
source = source.Substring(junk.Length, source.Length - junk.Length); // erase start
return source.Remove(source.IndexOf(']')); // erase end
}
}
Demo on DotNetFiddle

Searching strings in txt file

I have a .txt file with a list of 174 different strings. Each string has an unique identifier.
For example:
123|this data is variable|
456|this data is variable|
789|so is this|
etc..
I wish to write a programe in C# that will read the .txt file and display only one of the 174 strings if I specify the ID of the string I want. This is because in the file I have all the data is variable so only the ID can be used to pull the string. So instead of ending up with the example about I get just one line.
eg just
123|this data is variable|
I seem to be able to write a programe that will pull just the ID from the .txt file and not the entire string or a program that mearly reads the whole file and displays it. But am yet to wirte on that does exactly what I need. HELP!
Well the actual string i get out from the txt file has no '|' they were just in the example. An example of the real string would be: 0111111(0010101) where the data in the brackets is variable. The brackets dont exsist in the real string either.
namespace String_reader
{
class Program
{
static void Main(string[] args)
{
String filepath = #"C:\my file name here";
string line;
if(File.Exists(filepath))
{
StreamReader file = null;
try
{
file = new StreamReader(filepath);
while ((line = file.ReadLine()) !=null)
{
string regMatch = "ID number here"; //this is where it all falls apart.
Regex.IsMatch (line, regMatch);
Console.WriteLine (line);// When program is run it just displays the whole .txt file
}
}
}
finally{
if (file !=null)
file.Close();
}
}
Console.ReadLine();
}
}
}
Use a Regex. Something along the lines of Regex.Match("|"+inputString+"|",#"\|[ ]*\d+\|(.+?)\|").Groups[1].Value
Oh, I almost forgot; you'll need to substitute the d+ for the actual index you want. Right now, that'll just get you the first one.
The "|" before and after the input string makes sure both the index and the value are enclosed in a | for all elements, including the first and last. There's ways of doing a Regex without it, but IMHO they just make your regex more complicated, and less readable.
Assuming you have path and id.
Console.WriteLine(File.ReadAllLines(path).Where(l => l.StartsWith(id + "|")).FirstOrDefault());
Use ReadLines to get a string array of lines then string split on the |
You could use Regex.Split method
FileInfo info = new FileInfo("filename.txt");
String[] lines = info.OpenText().ReadToEnd().Split(' ');
foreach(String line in lines)
{
int id = Convert.ToInt32(line.Split('|')[0]);
string text = Convert.ToInt32(line.Split('|')[1]);
}
Read the data into a string
Split the string on "|"
Read the items 2 by 2: key:value,key:value,...
Add them to a dictionary
Now you can easily find your string with dictionary[key].
first load the hole file to a string.
then try this:
string s = "123|this data is variable| 456|this data is also variable| 789|so is this|";
int index = s.IndexOf("123", 0);
string temp = s.Substring(index,s.Length-index);
string[] splitStr = temp.Split('|');
Console.WriteLine(splitStr[1]);
hope this is what you are looking for.
private static IEnumerable<string> ReadLines(string fspec)
{
using (var reader = new StreamReader(new FileStream(fspec, FileMode.Open, FileAccess.Read, FileShare.Read)))
{
while (!reader.EndOfStream)
yield return reader.ReadLine();
}
}
var dict = ReadLines("input.txt")
.Select(s =>
{
var split = s.Split("|".ToArray(), 2);
return new {Id = Int32.Parse(split[0]), Text = split[1]};
})
.ToDictionary(kv => kv.Id, kv => kv.Text);
Please note that with .NET 4.0 you don't need the ReadLines function, because there is ReadLines
You can now work with that as any dictionary:
Console.WriteLine(dict[12]);
Console.WriteLine(dict[999]);
No error handling here, please add your own
You can use Split method to divide the entire text into parts sepparated by '|'. Then all even elements will correspond to numbers odd elements - to strings.
StreamReader sr = new StreamReader(filename);
string text = sr.ReadToEnd();
string[] data = text.Split('|');
Then convert certain data elements to numbers and strings, i.e. int[] IDs and string[] Strs. Find the index of the given ID with idx = Array.FindIndex(IDs, ID.Equals) and the corresponding string will be Strs[idx]
List <int> IDs;
List <string> Strs;
for (int i = 0; i < data.Length - 1; i += 2)
{
IDs.Add(int.Parse(data[i]));
Strs.Add(data[i + 1]);
}
idx = Array.FindIndex(IDs, ID.Equals); // we get ID from input
answer = Strs[idx];

Categories

Resources