c# splitting and retrieving values from a string - c#

I have a string like this:
"http://localhost:55164/Images/photos/2/2.jpg"
I need to retrieve the filename and the 2 out of the /2/ and put them into their own strings. I've been messing around with StringBuilder and replace and substr to no avail since the filename length is variable. Anyone have a quick way to do this?
Thanks

string link = "http://localhost:55164/Images/photos/2/2.jpg"; // your link
string[] x = link.Split('/'); // split it into pieces at the slash
string filename = (x.Length >= 1) ? x[x.Length - 1] : null; // get the last part
string dir = (x.Length >= 2) ? x[x.Length - 2] : null; // get the 2nd last part
Edit, checked the array length before trying to access it's pieces like someone suggested below in the comments.

You could cheat and use the Path class. This is easier and adds extra readability at the same time.
string path = "http://localhost:55164/Images/photos/2/2.jpg";
Console.WriteLine(Path.GetFileName(path));
string[] dirSplit = Path.GetDirectoryName(path).Split('\\');
Console.WriteLine(dirSplit[dirSplit.Length - 1]);

I would suggest using the Path class:
string filename = Path.GetFileName(s);
string dir = Path.GetDirectoryName(s).GetFileName(s);

One quick way you could do with would be to split the string by the forward slash.
In this way you'll know that the last item in the array and the second-to-last item will be what you require.
Such that:
string url = "http://localhost:55164/Images/photos/2/2.jpg";
string[] urlParts = url.Split('/');
string file = urlParts[urlParts.length -1];

use Split function with '/' as separator and take 2 last elements of the array.
string s = "";
string[] arr = s.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
string ans = "";
if (arr.Length > 1)
ans = arr[arr.Length - 1] + arr[arr.Length - 2];

I suggest you use the System.Uri class which is tailor-made for this purpose (providing easy access to parts of a URI), e.g.,
Uri uri = new Uri("http://localhost:55164/Images/photos/2/2.jpg");
string[] segments = uri.Segments;
foreach (string segment in segments)
{
Console.WriteLine(segment.Trim('/'));
}

Related

Append string and format Array Values

I have a array with values and want to append a link to all the values of array assign back the value to same array.
string [] files = null; // will contain array of string values
string[] attachmentFilePath = files;
string[] attachmentFileName = files;
I want to append "http://www.google.com" with every value in the files array and assign it to attachmentFilePath.
I have tried a lot using string.format("google.com",files[index])
for(var i = 0; i<files.count();i++)
{
files[index] = string.format("http://www.google.com",files[index]);
}
tried a lot but some or the other way the code gives error or index out of bounds or null reference exception.
I need the string to appended like 'http://www.google.com/files.value'
Can anyone help me out ?
Using string.Format requires the string to be in the proper format for formatting:
string.Format("some string with place holder: {0}","some string to put");
If your string does not have the placeholders (as in your case) it doesn't do anything. Read more about string.Format
Solutions:
Simple for loop:
var yourString = "http://www.google.com/";
var attachmentFilePath = new string[files.Length];
for(int i = 0; i < files.Length; i++)
{
attachmentFilePath[i] = yourString + files[i];
}
Linq:
var yourString = "http://www.google.com/";
var attachmentFilePath = files.Select(s => yourString + s).ToArray();
And of course you can correctly use string.Format to any of these two solutions where appending the strings. Just see it is has the place holder in the place you want
You can accomplish the task at hand with something along the lines of:
string[] attachmentFilePath = files.Select(x => $"http://www.google.com/{x}")
.ToArray();

How to get the next word in a string?

I feel pretty foolish for asking a seemingly easy question Sigh but for the life of me I cant figure it out.
string myString = "10/27/14 TheNextString DontWantThisString";
Assume that the second string is unknown(as in it could be any type of word). How could I get the second word after the last index of the date.
Sorry this Is probably a weird question.
var lastLine = line.Substring(idx + "date:".Length + 1, 14);
var lastChar = lastLine.Substring(lastLine.Length-1, 1);
headerName = lastLine.Substring(lastLine.LastIndexOf(lastChar), +1);
Heres some of my code for a little context if you will.
You want String.Split().
string[] delimiters = new string[] {" "};
string[] words = myString.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
string myString = "10/27/14 TheNextString DontWantThisString";
var values = Regex.Split(myString , #"\s+");
if (values.Count > 1)
Console.WriteLine(values[1]);
This should work (haven't tested the code, but you get the idea).
String result[] = myString.split(null);
result[1] will return what you need.
See: String.SplitMethod
namespace SplitDemo
{
class Program
{
static void Main(string[] args)
{
var myString = "10/27/14 TheNextString DontWantThisString";
var stringArray = myString.Split(default(char[]), StringSplitOptions.RemoveEmptyEntries);
var word = stringArray[1];
}
}
}
Something like this should work for you. This splits the string into an array, using a space as the separator, removes any empty matches, and then gets the second item.
myString.Split(new[]{' '}, StringSplitOptions.RemoveEmptyEntries)[1]
http://msdn.microsoft.com/en-us/library/ms131448.aspx

c# how to solve a issue using substring

How to solve substring issue. I have tried to code correctly but not working for me.
The file name is bad_filename.xml or good_filename.xml
what i want is to use substring to result "bad" or "good" where _filename.xml should be removed. how to do this?
From: bad_filename.xml or good_filename.xml
to: bad or good
Try this
string s = "bad_filename.xml";
string sub = s.Substring(0, s.IndexOf("_"));
string sub2 = string.Concat((s.TakeWhile(x => x != '_')));
string sub3 = s.Split('_')[0];
I've given three ways pick any one of your choice
Note: Way (1) will throw exception when string doesn't contain _ you need to check index > -1
Try this, as I have mention in Question comment.
var result = filename.Split('_')[0];
var result = filename.Split('_')[0];
Use the Path class to get the file name and string.Split to get the first part:
string fileNameWOE = Path.GetFileNameWithoutExtension("bad_filename.xml");
string firstPart = fileNameWOE.Split('_')[0];
try this
string input = "bad_filename.xml"
string sub = input.Substring(0, input.IndexOf("_"));
Console.WriteLine("Substring: {0}", sub);
You can use this code for substring.
string a="bad_filename.xml ";
int index=a.IndexOf('_');
if (index != -1)
{
string filename = a.Substring(0,index);
}
output is bad
do it like this :
string[] strArr = stringFileName.Split('_');
string[] strArr = bad_filename.xml.Split('_');
strArr[0] is "bad"
and
string[] strArr = good_filename.xml.Split('_');
strArr[0] is "good"

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

Get the different substrings from one main string

I have the following main string which contains link Name and link URL. The name and url is combined with #;. I want to get the string of each link (name and url i.e. My web#?http://www.google.com), see example below
string teststring = "My web#;http://www.google.com My Web2#;http://www.bing.se Handbooks#;http://www.books.se/";
and I want to get three different strings using any string function:
My web#?http://www.google.com
My Web2#?http://www.bing.se
Handbooks#?http://www.books.de
So this looks like you want to split on the space after a #;, instead of splitting at #; itself. C# provides arbitrary length lookbehinds, which makes that quite easy. In fact, you should probably do the replacement of #; with #? first:
string teststring = "My web#;http://www.google.com My Web2#;http://www.bing.se Handbooks#;http://www.books.se/";
teststring = Regex.Replace(teststring, #"#;", "#?");
string[] substrings = Regex.Split(teststring, #"(?<=#\?\S*)\s+");
That's it:
foreach(var s in substrings)
Console.WriteLine(s);
Output:
My web#?http://www.google.com
My Web2#?http://www.bing.se
Handbooks#?http://www.books.se/
If you are worried that your input might already contain other #? that you don't want to split on, you can of course do the splitting first (using #; in the pattern) and then loop over substrings and do the replacement call inside the loop.
If these are constant strings, you can just use String.Substring. This will require you to count letters, which is a nuisance, in order to provide the right parameters, but it will work.
string string1 = teststring.Substring(0, 26).Replace(";","?");
If they aren't, things get complicated. You could almost do a split with " " as the delimiter, except that your site name has a space. Do any of the substrings in your data have constant features, such as domain endings (i.e. first .com, then .de, etc.) or something like that?
If you have any control on the input format, you may want to change it to be easy to parse, for example by using another separator between items, other than space.
If this format can't be changed, why not just implement the split in code? It's not as short as using a RegEx, but it might be actually easier for a reader to understand since the logic is straight forward.
This will almost definitely will be faster and cheaper in terms of memory usage.
An example for code that solves this would be:
static void Main(string[] args)
{
var testString = "My web#;http://www.google.com My Web2#;http://www.bing.se Handbooks#;http://www.books.se/";
foreach(var x in SplitAndFormatUrls(testString))
{
Console.WriteLine(x);
}
}
private static IEnumerable<string> SplitAndFormatUrls(string input)
{
var length = input.Length;
var last = 0;
var seenSeparator = false;
var previousChar = ' ';
for (var index = 0; index < length; index++)
{
var currentChar = input[index];
if ((currentChar == ' ' || index == length - 1) && seenSeparator)
{
var currentUrl = input.Substring(last, index - last);
yield return currentUrl.Replace("#;", "#?");
last = index + 1;
seenSeparator = false;
previousChar = ' ';
continue;
}
if (currentChar == ';' && previousChar == '#')
{
seenSeparator = true;
}
previousChar = currentChar;
}
}

Categories

Resources