I was trying to remove last part of a string but failed.Here string named D:\software\VS2012\newtext.txt and i want to trim last section of string so here newtext.txt . I should get D:\software\VS2012 but how to do it in c#.When i tried it is removing all the string that has '\'. Here is what i did in c#
string str = #"D:\softwares\VS2012\newtext.txt";
str= str.Remove(str.IndexOf('\\'));
Console.WriteLine(str);
There is a premade function for this in the framework
string str = #"D:\softwares\VS2012\newtext.txt";
string path = System.IO.Path.GetDirectoryName(str);
(Reference)
Note that your original code does not work because you are removing from the first backslash, not the last. Substitute this line to make your code work
str = str.Remove(str.LastIndexOf('\\'));
Try using System.IO.Path.GetDirectoryName(string):
string dirname= System.IO.Path.GetDirectoryName(#"D:\softwares\VS2012\newtext.txt");
For removing a known portion of a string you can simply use the Replace.
In your case:
str = str.Replace("\\newtext.txt", ""); //this will give you the same result of the System.IO.Path.GetDirectoryName already suggested by gmiley, but it's more in a string context as per your question
Though if you want to remove the last part of a string by the last encounterd known character then the suggested "LastIndexOff('\')" method already suggested along with the Remove.
If you want to use a delimiter method, so depending on the delimiter character but not on the string format (in your case path format) the LastIndexOff(char) is the best option.
Although you could also split the string into an array and then rejoin the array after removing the last element:
var delmimter = '\\';
var strAy = str.Split(char);
str = String.Join('\\', strAy.SkipLast(1).ToArray());
With this method you don't need to rely on the existence of the delimiter char in the string and the result is always without the delimiter char at the end.
Besides, you can easily create an extension with the delimiter as a parameter.
We should check the existance of the char also
string str = #"D:\softwares\VS2012\newtext.txt";
int rstr = str.LastIndexOf('\\');
if (rstr>0) str= str.Remove(rstr);
Console.WriteLine(str);
Related
I have an issue with a string containing the plus sign (+).
I want to split that string (or if there is some other way to solve my problem)
string ColumnPlusLevel = "+-J10+-J10+-J10+-J10+-J10";
string strpluslevel = "";
strpluslevel = ColumnPlusLevel;
string[] strpluslevel_lines = Regex.Split(strpluslevel, "+");
foreach (string line in strpluslevel_lines)
{
MessageBox.Show(line);
strpluslevel_summa = strpluslevel_summa + line;
}
MessageBox.Show(strpluslevel_summa, "summa sumarum");
The MessageBox is for my testing purpose.
Now... The ColumnPlusLevel string can have very varied entry but it is always a repeated pattern starting with the plus sign.
i.e. "+MJ+MJ+MJ" or "+PPL14.1+PPL14.1+PPL14.1" as examples.
(It comes form Another software and I cant edit the output from that software)
How can I find out what that pattern is that is being repeated?
That in this exampels is the +-J10 or +MJ or +PPL14.1
In my case above I have tested it by using only a MessageBox to show the result but I want the repeated pattering stored in a string later on.
Maybe im doing it wrong by using Split, maybe there is another solution.
Maybe I use Split in the wrong way.
Hope you understand my problem and the result I want.
Thanks for any advice.
/Tomas
How can I find out what that pattern is that is being repeated?
Maybe i didn't understand the requirement fully, but isn't it easy as:
string[] tokens = ColumnPlusLevel.Split(new[]{'+'}, StringSplitOptions.RemoveEmptyEntries);
string first = tokens[0];
bool repeatingPattern = tokens.Skip(1).All(s => s == first);
If repeatingPattern is true you know that the pattern itself is first.
Can you maybe explain how the logic works
The line which contains tokens.Skip(1) is a LINQ query, so you need to add using System.Linq at the top of your code file. Since tokens is a string[] which implements IEnumerable<string> you can use any LINQ (extension-)method. Enumerable.Skip(1) will skip the first because i have already stored that in a variable and i want to know if all others are same. Therefore i use All which returns false as soon as one item doesn't match the condition(so one string is different to the first). If all are same you know that there is a repeating pattern which is already stored in the variable first.
You should use String.Split function :
string pattern = ColumnPlusLevel.Split("+")[0];
...but it is always a repeated pattern starting with the plus sign.
Why do you even need String.Split() here if the pattern always only repeats itself?
string input = #"+MJ+MJ+MJ";
int indexOfSecondPlus = input.IndexOf('+', 1);
string pattern = input.Remove(indexOfSecondPlus, input.Length - indexOfSecondPlus);
//pattern is now "+MJ"
No need of string split, no need to use LinQ
String has a method called Split which let's you split/divide the string based on a given character/character-set:
string givenString = "+-J10+-J10+-J10+-J10+-J10"'
string SplittedString = givenString.Split("+")[0] ///Here + is the character based on which the string would be splitted and 0 is the index number
string result = SplittedString.Replace("-","") //The mothod REPLACE replaces the given string with a targeted string,i added this so that you can get the numbers only from the string
I need to get the data which is outside of parenthesis
string data = "English(Language)";
string result= "English";
The result should display the text "English".
I tried with Regex but not able to get the desired result.
Easiest solution that I can think of:
string data = "English(Language)";
string result = data.Substring(0, data.IndexOf('('));
That is of course, if you never need the data within the parenthesis.
Another way to do it is by using String.Split:
string data = "English(Language)";
string result = data.Split('(')[0];
This is marginally slower than the first example since it needs to allocate memory for an array.
The third way to do it is via regular-expressions:
string data = "English(Language)";
var pattern = new Regex("(\\w+\\s?)\\((\\w+)\\)", RegexOptions.Compiled);
string result = pattern.Match(data).Groups[1].Value;
This is the slowest of all the examples, but captures both "English" and "Language". It also allows for whitespace \s? between English and (Language).
A great tool for testing regular expressions is RegexPal, just remember to escape everything when you move it over to C#.
Here is a fiddle, testing the performance of all options.
Try:
string input = "English(Language)";
string regex = "(\\(.*\\))";
string output = Regex.Replace(input, regex, "");
You will need that:
using System.Text.RegularExpressions;
If you dont bother to use Regex, the below solution works fine.
string data = "English(Language)";
string result = Regex.Match(data, #"(.*)\(.*\)").Groups[1].Value;
Console.WriteLine(result); // English
Hi take a look at the Split methods:
string data = "English(Language)";
string result= "English";
var value = data.Split('(').First();
Console.WriteLine (value);
Result :
English
xd or just:
string data = "English(Language)";
string result = data.Replace("(Language)", "");
I am using Visual studio 2010.
I need to replace some part of my string, thus I should find the specific charter in my string.
but .find is not available for me.
What should I do, is there any specific library for that?
string selected="ddddtttjjj";
selected.find("t");
C#, String.IndexOf
string str = "abcdefg";
var ix = str.IndexOf("d");
Console.WriteLine("Ix=" + ix);
// output
//Ix=3
http://msdn.microsoft.com/en-us/library/k8b1470s(v=vs.110).aspx
but, if you want to repleace a substring you can use. "String.Replace"
string str = "abcdefg";
str = str.Replace("d","xDx");
Console.WriteLine(str);
// ouput
// abcxDxefg
http://msdn.microsoft.com/en-us/library/fk49wtc1(v=vs.110).aspx
note that String.Replace Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.
How to get text before a symbol in string ? Any ideas?
e.g. acsbkjb/123kbvh/123jh/
get text before first - "/"
Try this
string ss = myString.Split('/')[0];
You can use Substring() method to get the required part of the string.
String text="acsbkjb/123kbvh/123jh/";
int index=text.IndexOf('/');
String text2="";
if(index>=0)
text2=text.Substring(0,index);
get substring like
youstring.Substring(0,yourstring.IndexOf('/'));
The IEnumerable approach
string str = "acsbkjb/123kbvh/123jh/";
var result = new string(str.TakeWhile(a => a != '/').ToArray());
Console.WriteLine(result);
If there are no forward slashes this works without need to check the return of IndexOf
EDIT Keep this answer just as an example because the efficiency of this approach is really worse. IndexOf works faster also if you add an if statement to check the return value.
string text = "acsbkjb/123kbvh/123jh/";
string text2 = text.Substring(0, text.IndexOf("/"));
Ill lose to much time since i don`t have too much experience in manipulating with strings/chars.
i have
string original = "1111,2222,"This is test work")";
i need
string first = "1111";
string second = "2222";
string name = "This is test work";
C# ASP.NET
Use string.Split() - your pattern is simple (split on comma), there is no need to use a RegEx here:
var parts = original.Split(',');
first = parts[0];
second = parts[1];
name = parts[2].TrimEnd(')'); //in case you really wanted to remove that last bracket
Use the String.Split method:
string[] values = original.Split(new Char [] {','});
This will break apart your string at every comma and return a string array containing each part. To access:
string first = values[0];
string second = values[1];
string name = values[2];