I want to be able to extract the name of a sub-directory of a URL and save it to a string from the server-side in ASP.NET C#. For example, lets say I have a URL that looks like this:
http://www.example.com/directory1/directory2/default.aspx
How would I get the value 'directory2' from the URL?
Uri class has a property called segments:
var uri = new Uri("http://www.example.com/directory1/directory2/default.aspx");
Request.Url.Segments[2]; //Index of directory2
This is a sorther code:
string url = (new Uri(Request.Url,".")).OriginalString
I'd use .LastIndexOf("/") and work backwards from that.
You can use System.Uri to extract the segments of the path. For example:
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var uri = new System.Uri("http://www.example.com/directory1/directory2/default.aspx");
}
}
Then the property "uri.Segments" is a string array (string[]) containing 4 segments like this: ["/", "directory1/", "directory2/", "default.aspx"].
You can use split method of string class to split it on /
Try this if you want to pick page directory
string words = "http://www.example.com/directory1/directory2/default.aspx";
string[] split = words.Split(new Char[] { '/'});
string myDir=split[split.Length-2]; // Result will be directory2
Here is example from MSDN. How to use split method.
using System;
public class SplitTest
{
public static void Main()
{
string words = "This is a list of words, with: a bit of punctuation" +
"\tand a tab character.";
string [] split = words.Split(new Char [] {' ', ',', '.', ':', '\t' });
foreach (string s in split)
{
if (s.Trim() != "")
Console.WriteLine(s);
}
}
}
// The example displays the following output to the console:
// This
// is
// a
// list
// of
// words
// with
// a
// bit
// of
// punctuation
// and
// a
// tab
// character
Related
what can I do to achieve the output on right side as shown on image? Do note that later on there will be many data with this kind of inconsistent alignment and is there any way to loop all text along with adjusted alignment as shown on right side of image?
You could use Regex to replace occurrence of multiple whitespace (2 or more,including tab) with a single whitespace. For example,
var result = Regex.Replace(str,"[\t ]{2,}"," ");
The common forms of whitespace could divided into
Space
Tab(\t)
NewLine(\n)
Return(\t)
In the above scenario, it looks like you need to replace all the Space (2 or more) and Tab characters with a single whitespace character (and ignore the NewLine/Return characters). For the purpose, you could use Regex as shown in the code above
Short Answer, use Trim() or TrimEnd, but here is the way I would do your task using my Nuget package you can convert this to string.Split() if you don't want to use a Nuget package:
Nuget Package:
DataJuggler.Core.UltimateHelper (.Net Framework)
DataJuggler.UltimateHelper.Core (.Net Core)
.Net Framework is shown
// source input
string inputFileText = "blah blah blah blah blah " + Environment.NewLine + "blah blah blah blah blah";
// parse the lines
List<TextLine> lines = WordParser.GetTextLines(inputFileText);
// If the lines collection exists and has one or more items
if (ListHelper.HasOneOrMoreItems(lines))
{
// Iterate the collection of TextLine objects
foreach (TextLine line in lines)
{
// Get the words
List<Word> words = WordParser.GetWords(line.Text);
}
}
Then you can do what you want with each Line, and each Line contains a list of Words (string text).
Here is the code the Nuget package uses, if you would rather copy it:
public static List<TextLine> GetTextLines(string sourceText)
{
// initial value
List<TextLine> textLines = new List<TextLine>();
// typical delimiter characters
char[] delimiterChars = Environment.NewLine.ToCharArray();
// local
int counter = -1;
// verify the sourceText exists
if (!String.IsNullOrEmpty(sourceText))
{
// Get the list of strings
string[] linesOfText = sourceText.Split(delimiterChars);
// now iterate the strings
foreach (string lineOfText in linesOfText)
{
// local
string text = lineOfText;
// increment the counter
counter++;
// add every other row
if ((counter % 2) == 0)
{
// Create a new TextLine
TextLine textLine = new TextLine(text);
// now add this textLine to textLines collection
textLines.Add(textLine);
}
}
}
// return value
return textLines;
}
public static List<Word> GetWords(string sourceText, char[] delimeters = null, bool allowEmptyStrings = false)
{
// initial value
List<Word> words = new List<Word>();
// typical delimiter characters
char[] delimiterChars = { ' ','-','/', ',', '.', '\t' };
// if the delimter exists
if (NullHelper.Exists(delimeters))
{
// use these delimters
delimiterChars = delimeters;
}
// verify the sourceText exists
if (!String.IsNullOrEmpty(sourceText))
{
// Get the list of strings
string[] strings = sourceText.Split(delimiterChars);
// now iterate the strings
foreach(string stringWord in strings)
{
// verify the word is not an empty string or a space
if ((allowEmptyStrings) || (TextHelper.Exists(stringWord)))
{
// Create a new Word
Word word = new Word(stringWord);
// now add this word to words collection
words.Add(word);
}
}
}
// return value
return words;
}
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);
}
}
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);
}
}
I need to demilitarise text by a single character, a comma. But I want to only use that comma as a delimiter if it is not encapsulated by quotation marks.
An example:
Method,value1,value2
Would contain three values: Method, value1 and value2
But:
Method,"value1,value2"
Would contain two values: Method and "value1,value2"
I'm not really sure how to go about this as when splitting a string I would use:
String.Split(',');
But that would demilitarise based on ALL commas. Is this possible without getting overly complicated and having to manually check every character of the string.
Thanks in advance
Copied from my comment: Use an available csv parser like VisualBasic.FileIO.TextFieldParser or this or this.
As requested, here is an example for the TextFieldParser:
var allLineFields = new List<string[]>();
string sampleText = "Method,\"value1,value2\"";
var reader = new System.IO.StringReader(sampleText);
using (var parser = new Microsoft.VisualBasic.FileIO.TextFieldParser(reader))
{
parser.Delimiters = new string[] { "," };
parser.HasFieldsEnclosedInQuotes = true; // <--- !!!
string[] fields;
while ((fields = parser.ReadFields()) != null)
{
allLineFields.Add(fields);
}
}
This list now contains a single string[] with two strings. I have used a StringReader because this sample uses a string, if the source is a file use a StreamReader(f.e. via File.OpenText).
You can try Regex.Split() to split the data up using the pattern
",|(\"[^\"]*\")"
This will split by commas and by characters within quotes.
Code Sample:
using System;
using System.Linq;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
string data = "Method,\"value1,value2\",Method2";
string[] pieces = Regex.Split(data, ",|(\"[^\"]*\")").Where(exp => !String.IsNullOrEmpty(exp)).ToArray();
foreach (string piece in pieces)
{
Console.WriteLine(piece);
}
}
}
Results:
Method
"value1,value2"
Method2
Demo
I want to seperate multiple values from a gridview control and show it in four textboxes. Is that possible?
Right now I get this value:
With this code:
var lblRef = new Label
{
Text = ((Label) row.FindControl("LabelAssignmentReference")).Text
};
string valueTextBox = lblRef.Text;
int indexOfRefSwe = valueTextBox.IndexOf(",", StringComparison.Ordinal);
string valueRef = valueTextBox.Substring(0, indexOfRefSwe);
TextBoxReference.Text = valueRef;
But how do i get it in multiple values? ` TextBoxReference.Text = valueRef;
TextBoxRefPhone.Text = "??";
TextBoxRefEmail.Text = "??";
TextBoxRefDesc.Text = "??";`
This should get you started.
string[] splits = lblRef.Text.Split(',');
Console.WriteLine(splits[0]); // refname
Console.WriteLine(splits[1]); // 08712332
Console.WriteLine(splits[2]); // ref#gmail.com
Console.WriteLine(splits[3]); // refdescription
I suggest also adding validation checks to make sure you don't get any errors, such as checking that splits.Length == 4 as expected.
Note that the spaces will be included in the beginning of the last three elements of splits. You can eliminate those using the Trim method, or by providing an array of delimiters new[] {',', ' '} to the split function and ignore empty elements (there's an overload for that).
There is System.String.Split()-method:
string[] parts = str.Split(new char[] {','});
Afterwards, work on the parts.
Example from MSDN
using System;
public class SplitTest {
public static void Main() {
string words = "This is a list of words, with: a bit of punctuation" +
"\tand a tab character.";
string [] split = words.Split(new Char [] {' ', ',', '.', ':', '\t' });
foreach (string s in split) {
if (s.Trim() != "")
Console.WriteLine(s);
}
}
}
you can do as below
var values = lblRef.Text.Split(',');
TextBoxRefPhone.Text = values[0];
if(values.Length>0)
TextBoxRefEmail.Text =values[1];
if(values.Length>1)
TextBoxRefDesc.Text = values[2];
Edit
there is a Split overload method which accept params. so we can give one character
public string[] Split(params char[] separator);
The params keyword lets you specify a method parameter that takes an
argument where the number of arguments is variable.