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"
Related
I have the following string
string a = #"\\server\MainDirectory\SubDirectoryA\SubdirectoryB\SubdirectoryC\Test.jpg";
I'm trying to remove part of the string so in the end I want to be left with
string a = #"\\server\MainDirectory\SubDirectoryA\SubdirectoryB";
So currently I'm doing
string b = a.Remove(a.LastIndexOf('\\'));
string c = b.Remove(b.LastIndexOf('\\'));
Console.WriteLine(c);
which gives me the correct result. I was wondering if there is a better way of doing this? because I'm having to do this in a fair few places.
Note: the SubdirectoryC length will be unknown. As it is made of the numbers/letters a user inputs
There is Path.GetDirectoryName
string a = #"\\server\MainDirectory\SubDirectoryA\SubdirectoryB\SubdirectoryC\Test.jpg";
string b = Path.GetDirectoryName(Path.GetDirectoryName(a));
As explained in MSDN it works also if you pass a directory
....passing the returned path back into the GetDirectoryName method will
result in the truncation of one folder level per subsequent call on
the result string
Of course this is safe if you have at least two directories level
Heyho,
if you just want to get rid of the last part.
You can use :
var parentDirectory = Directory.GetParent(Path.GetDirectoryName(path));
https://msdn.microsoft.com/de-de/library/system.io.directory.getparent(v=vs.110).aspx
An alternative answer using Linq:
var b = string.Join("\\", a.Split(new string[] { "\\" }, StringSplitOptions.None)
.Reverse().Skip(2).Reverse());
Some alternatives
string a = #"\\server\MainDirectory\SubDirectoryA\SubdirectoryB\SubdirectoryC\Test.jpg";
var b = Path.GetFullPath(a + #"\..\..");
var c = a.Remove(a.LastIndexOf('\\', a.LastIndexOf('\\') - 1));
but I do find this kind of string extensions generally usefull:
static string beforeLast(this string str, string delimiter)
{
int i = str.LastIndexOf(delimiter);
if (i < 0) return str;
return str.Remove(i);
}
For such repeated tasks, a good solution is often to write an extension method, e.g.
public static class Extensions
{
public static string ChopPath(this string path)
{
// chopping code here
}
}
Which you then can use anywhere you need it:
var chopped = a.ChopPath();
I have a string
String data="CE|2014-2015|ClassA"
I need output like
string Batch="2014-2015"
string Class="ClassA"
How can I achieve it?? I tried a lot string,Split() function. But I did not get expected output.Please help me out
I tried,
string s = "CE|2014-2015|Class1";
string[] words = s.Split('|| ');
This should work for you
string[] splitted = data.Split('|');
string Batch = splitted[1];
string Class = splitted[2];
Your solution is wrong because: '|| ' is not a valid char and it won't even compile. You should split on | and take second and third value from splitted values
You can do the following
string data = "CE|2014-2015|ClassA";
string[] split = data.Split('|');
string Batch=split[1];
string Class = split[2];
Hope it works for you.
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
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);
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('/'));
}