c# how to get one value from substring - c#

How to solve this?
What i want to change this :
C:\files\team\business\dev\Source\systems\extension\destination\1.0.1.1\
to new value:
value = "1.0.11";

You could just get the Name of the corresponding DirectoryInfo:
string path = #"C:\files\team\business\dev\Source\systems\extension\destination\1.0.1.1\";
string version = new DirectoryInfo(path).Name;

Alternative method:
var path = #"C:\files\team\business\dev\Source\systems\extension\destination\1.0.1.1\";
var value = Path.GetFileName(path.TrimEnd(new[]{'/','\\'}));
// OUTPUT: 1.0.1.1
This basically removes any last directory delimeters and then treats the last directory as a filename, so it returns the last directory.
Based on #JeppeStigNielsen's comments below, here's a better, platform independent alternative.
var value = Path.GetFileName(Path.GetDirectoryName(path));
This will work if there is a file name present as well.
var value = Path.GetFileName(Path.GetDirectoryName(".../1.0.1.1/somefile.etc"));
// returns 1.0.1.1

Darin's answer is great but as an alternative;
string s = #"C:\files\team\business\dev\Source\systems\extension\destination\1.0.1.1\";
string[] array = s.Split('\\');
Console.WriteLine(array[array.Length - 2]);
Output will be;
1.0.1.1
Here a DEMO.

Related

How should we reverse format & extract a string in C#?

Pretty sure we all do string.format and define some string in a specifed format.
I have a string which is always formatted in a way like this:
const string myString = string.Format("pt:{0}-first:{1}", inputString);
To get {0}, I can always check for pt:{ and read till }.
But what is the best/recommended way to extract {0} & {1} from the above variable myString ?
A Regex version of answer, but again, assuming your input doesnt contain '-'
var example = = "pt:hello-first:23";
var str = "pt:(?<First>[^-]+)-first:(?<Second>[^%]+)";
var match = new Regex(str).Match(example);
var first = match.Groups["First"].Value;
var second = match.Groups["Second"].Value;
It might be a good idea that you define what your variable can/cannot contain.
Not sure if this is the best way to do it, but it's the most obvious:
string example = "pt:123-first:456";
var split = example.Split('-');
var pt = split[0].Substring(split[0].IndexOf(':') + 1);
var first = split[1].Substring(split[1].IndexOf(':') + 1);
As Shawn said, if you can guarantee that the variables wont contain either : or - this will be adequate.

Replace specific string in large string

I'm writing a small WPF Application which helps my company to update costumer projects. I have a list of SQL-Files which I have to execute. Now these scripts are always written with a "USE [Insert_Database]". I read the whole content of a script into a string, but my Replace method doesn't seem to do anything.
string content = File.ReadAllText(file);
content.Replace("Insert_Database", Database.Name);
SqlScriptsList.Add(new SqlScriptModel {Name = Path.GetFileName(file), Path = file, ScriptContent = content});
String.Replace returns the modified string, so it should be:
content = content.Replace(....);
This method does not modify the value of the current instance.
Instead, it returns a new string in which all occurrences of oldValue
are replaced by newValue.
You can use replace function as follow on strings
str = str.Replace("oldstr","newstr");
if oldstr is found in the str then it will be replaced by new str
You aren't using new value when you call replace.
string content = File.ReadAllText(file);
content = content.Replace("Insert_Database", Database.Name);
SqlScriptsList.Add(new SqlScriptModel {Name = Path.GetFileName(file), Path = file, ScriptContent = content});
for reference: the MSDN doc for replace https://msdn.microsoft.com/en-us/library/system.string.replace(v=vs.110).aspx

Split a string at 2 points

I have a file called file_test1.txt and I want to extract just test1 from the name and place it in a string. Whats the best way of doing this?
E.g.
string fullfile = #"C:\file_test1.txt";
string section = [test1] from fullfile; // <- expected result
I want to be able to split on 'file_' and '.txt' as the 'test1' section could be larger or smaller however the 'file_' and '.txt' will always be the same.
Try Path.GetFileNameWithoutExtension(fullfile).Substring(5) (or Substring("TEMPLATE_PREFIX".Length))
You can try spilt
var test = Path.GetFileNameWithoutExtension(fullfile).split('_')[1];
Try following
string fullfile = #"C:\file_test1.txt";
var name = fullfile.Substring(8,fullfile.Length-12)
As c:\file_ and .txt are fixed, You can take Substring starting at index 8 (skip leading name), upto length of total string length - 12 (12 => length of leading name, and trailing extension)
Thought I'd give a solution that uses Split and handles files with multiple underscores:
string.Join("_", Path.GetFileNameWithoutExtension(file).Split('_').Skip(1));
String.Split() works quite well for my uses:
http://msdn.microsoft.com/en-us/library/b873y76a.aspx
Obviously many ways to accomplish this. Here's yet another approach:
string fullfile = #"C:\file_test1.txt";
int index1 = fullfile.LastIndexOf("file_");
if (index1 != -1)
{
int index2 = fullfile.IndexOf(".", index1);
if (index2 != -1)
{
string section = fullfile.Substring(index1 + 5, index2 - index1 - 5);
}
}
You could also get "test1", or any subsequent filename (assuming your file naming convention remains constant!) using this regular expression:
var defaultRegex = new Regex(#"(?<=_).*(?=.txt)");
var matches = defaultRegex.Matches(fullfile);
var match = matches[0].Value;
The regular expression:
(?<=_).*(?=.txt)
uses positive look behind to find text preceded by '_', and also positive lookahead to find text which has '.txt' ahead of it.

Get contents after last slash

I have strings that have a directory in the following format:
C://hello//world
How would I extract everything after the last / character (world)?
string path = "C://hello//world";
int pos = path.LastIndexOf("/") + 1;
Console.WriteLine(path.Substring(pos, path.Length - pos)); // prints "world"
The LastIndexOf method performs the same as IndexOf.. but from the end of the string.
using System.Linq;
var s = "C://hello//world";
var last = s.Split('/').Last();
There is a static class for working with Paths called Path.
You can get the full Filename with Path.GetFileName.
or
You can get the Filename without Extension with Path.GetFileNameWithoutExtension.
Try this:
string worldWithPath = "C://hello//world";
string world = worldWithPath.Substring(worldWithPath.LastIndexOf("/") + 1);
I would suggest looking at the System.IO namespace as it seems that you might want to use that. There is DirectoryInfo and FileInfo that might be of use here, also. Specifically DirectoryInfo's Name property
var directoryName = new DirectoryInfo(path).Name;

Getting substring between two separators in an arbitrary position

I have following string:
string source = "Test/Company/Business/Department/Logs.tvs/v1";
The / character is the separator between various elements in the string. I need to get the last two elements of the string. I have following code for this purpose. This works fine. Is there any faster/simpler code for this?
CODE
static void Main()
{
string component = String.Empty;
string version = String.Empty;
string source = "Test/Company/Business/Department/Logs.tvs/v1";
if (!String.IsNullOrEmpty(source))
{
String[] partsOfSource = source.Split('/');
if (partsOfSource != null)
{
if (partsOfSource.Length > 2)
{
component = partsOfSource[partsOfSource.Length - 2];
}
if (partsOfSource.Length > 1)
{
version = partsOfSource[partsOfSource.Length - 1];
}
}
}
Console.WriteLine(component);
Console.WriteLine(version);
Console.Read();
}
Why no regular expression? This one is fairly easy:
.*/(?<component>.*)/(?<version>.*)$
You can even label your groups so for your match all you need to do is:
component = myMatch.Groups["component"];
version = myMatch.Groups["version"];
The following should be faster, as it only scans as much of the string as it needs to to find two / and it doesn't bother splitting up the whole string:
string component = "";
string version = "";
string source = "Test/Company/Business/Department/Logs.tvs/v1";
int last = source.LastIndexOf('/');
if (last != -1)
{
int penultimate = source.LastIndexOf('/', last - 1);
version = source.Substring(last + 1);
component = source.Substring(penultimate + 1, last - penultimate - 1);
}
That said, as with all performance questions: profile! Try the two side-by-side with a big list of real-life inputs and see which is fastest.
(Also, this will leave empty strings rather than throw an exception if there is no slash in the input... but throw if source is null, lazy me.)
Your approach is the most suitable one given that your are looking for substrings at a particular index. A LINQ expression to do the same in this case will likely not improve the code or its readability.
For reference, there is some great information from Microsoft here on working with strings and LINQ. In particular see the article here which covers some examples with both LINQ and RegEx.
EDIT: +1 For Matt's named group within RegEx approach... that's the nicest solution I've seen.
Your code mostly looks fine. A couple of points to note:
String.Split() will never return null, so you don't need the null check on it.
If the source string has fewer than two / characters, how would you deal with that? (The Original Post was updated to address this)
Do you really want to just output empty strings if your source string is null or empty (or invalid)? If you have specific expectations about the nature of the input, you may want to consider failing fast when those expectations are not met.
You could try something like this but I doubt it would be much faster. You could do some meassurements with System.Diagnostics.StopWatch to see if you feel the need.
string source = "Test/Company/Business/Department/Logs.tvs/v1";
int index1 = source.LastIndexOf('/');
string last = source.Substring(index1 + 1);
string substring = source.Substring(0, index1);
int index2 = substring.LastIndexOf('/');
string secondLast = substring.Substring(index2 + 1);
I would try
string source = "Test/Company/Business/Department/Logs.tvs/v1";
var components = source.Split('/').Reverse().Take(2);
String last = string.Empty;
var enumerable = components as string[] ?? components.ToArray();
if (enumerable.Count() == 2)
last = enumerable.FirstOrDefault();
var secondLast = enumerable.LastOrDefault();
Hope this will help
you can retrieve the last two words using the process as below:
string source = "Test/Company/Business/Department/Logs.tvs/v1";
String[] partsOfSource = source.Split('/');
if(partsOfSourch.length>2)
for(int i=partsOfSourch.length-2;i<=partsOfSource.length-1;i++)
console.writeline(partsOfSource[i]);

Categories