How to remove in elegance way second part of string starting from particular substring?
Ex.
We have string:
var someString = "ThisIsSomeString_v1_26102017";
as a result we want: ThisIsSomeString
I did that:
var someString = "ThisIsSomeString_v1_26102017";
var tokens = someString.SplitByLast("_v");
var result = tokens[0];
There is any clever way to do that? Some Trim or something?
I mean as a result I want to have first part of string. In this case separator is a "_v" substring. I want to drop everything after "_v" included this "_v".
Use string.Substring:
var result = someString.Substring(0, Math.Max(someString.IndexOf("_v"), 0));
Not any better than the Substring implementation, the Split might look like this:
var result = someString.Split(new[]{"_v"}, StringSplitOptions.None).First();
Do like this -
var result = str.Substring(0, str.LastIndexOf("_v"));
It will remove all the text after _v (including _v).
What's wrong with:
var result = input?.Split(new[] { "_v" }, StringSplitOptions.None)[0];
Related
Code first:
string myString = "<at>onePossibleName</at> some question here regarding <at>disPossibleName</at>"
// some code to handle myString and save it in myEditedString
Console.WriteLine(myEditedString);
//output now is: some question here regarding <at>disPossibleName</at>
I want to remove <at>onePossibleName</at> from myString. The string onePossibleName and disPossbileName could be any other string.
So far I am working with
string myEditedString = string.Join(" ", myString.Split(' ').Skip(1));
The problem here would be that if onePossibleName becomes one Possible Name.
Same goes for the try with myString.Remove(startIndex, count) - this is not the solution.
There will be different method depending on what you want, you can go with a IndexOf and a SubString, regex would be a solution too.
// SubString and IndexOf method
// Usefull if you don't care of the word in the at tag, and you want to remove the first at tag
if (myString.Contains("</at>"))
{
var myEditedString = myString.Substring(myString.IndexOf("</at>") + 5);
}
// Regex method
var stringToRemove = "onePossibleName";
var rgx = new Regex($"<at>{stringToRemove}</at>");
var myEditedString = rgx.Replace(myString, string.Empty, 1); // The 1 precise that only the first occurrence will be replaced
You could use this generic regular expression.
var myString = "<at>onePossibleName</at> some question here regarding <at>disPossibleName</at>";
var rg = new Regex(#"<at>(.*?)<\/at>");
var result = rg.Replace(myString, "").Trim();
This would remove all 'at' tags and the content between. The Trim() call is to remove any white space at the beginning/end of the string after the replacement.
string myString = "<at>onePossibleName</at> some question here regarding <at>disPossibleName</at>"
int sFrom = myString.IndexOf("<at>") + "<at>".Length;
int sTo = myString.IndexOf("</at>");
string myEditedString = myString.SubString(sFrom, sFrom - sTo);
Console.WriteLine(myEditedString);
//output now is: some question here regarding <at>disPossibleName</at>
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.
I have done something like:
var a = "77,82,83";
foreach (var group in a.Split(','))
{
a = group.Replace("83", string.Empty);
}
If i want to remove 83 but override last updated value and got output empty or remove value from that i passed to replace.
e.g var a = 77,82,83
want output like 77,82
Edit:
"83" can be in any position.
If you want output as string you don't need to Split. Just get the LastIndexOf the , character and perform Substring on the variable:
var a = "77,82,83";
var newString = a.Substring(0, a.LastIndexOf(',')); // 77,82
If you are unsure if the string has at least one ,, you can validate before performing a Substring:
var a = "77,82,83";
var lastIndex = a.LastIndexOf(',');
if (lastIndex > 0)
var newString = a.Substring(0, lastIndex);
Update:
If you want to remove specific values from any position:
Split the string -> Remove the values using Where -> Join them with , separator
a = string.Join(",", a.Split(',').Where(i => i != "83"));
Here's a fiddle
You might need to clarify the question slightly but I think you're asking for the following:
var a = "72,82,83";
var group = a.Split(',').ToList();
int position = group.FindIndex(p => p.Contains("83"));
group.RemoveAt(position);
You can make the item you're looking for in the Contains query a parameter.
I think the problem you're having with your original code is that the foreach is a loop over each item in the array, so you're trying to remove "83" on each pass.
i need to remove the url path starting from /deposit/jingdongpay.htm?bid=4089
'?' i just need /deposit/jingdongpay.htm.
It means that the url will remove anything that comes after .htm
Any idea how to do it.
In Python, you can use str.split():
url = "/deposit/jingdongpay.htm?bid=4089"
split_url = url.split('?')
>>> split_url
['/deposit/jingdongpay.htm', 'bid=4089']
>>> split_url[0]
'/deposit/jingdongpay.htm'
You can use the String.Split method:
string url = "/deposit/jingdongpay.htm?bid=4089";
string result = url.Split('?')[0];
Another approach would be to use String.Substring:
string result = url.Substring(0, url.IndexOf('?'));
Or maybe if you are interested in a LINQ solution:
string result = new string(url.TakeWhile(c => c != '?').ToArray());
result = "/deposit/jingdongpay.htm"
how can I get a value of the string after last'/'
string path=http://localhost:26952/Images/Users/John.jpg
I would like to have as a result something like :
John.jpg
I think using Path.GetFileName method is a better way instead of string manipulation.
string path = "http://localhost:26952/Images/Users/John.jpg";
var result = Path.GetFileName(path);
Console.WriteLine(result); // John.jpg
Split by '/' and get the last part:
var url = "http://localhost:26952/Images/Users/John.jpg";
var imageName = url.Split('/').Last();