How to get text until a symbol in string - c#

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("/"));

Related

How to get the string data which is outside of parenthesis in C#

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

how to remove last part of string in c#

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

Replace URL in a string

I'm a beginner in C# and I have the following string,
string url = "svn1/dev";
along with,
string urlMod = "ato-svn3-sslv3.of.lan/svn/dev"
I want to replace svn1 in url with "ato-svn3-sslv3.of.lan"
Although your question still has some inconsistent statements, I believe String.Replace is what you are looking for:
http://msdn.microsoft.com/en-us/library/fk49wtc1.aspx
url = url.Replace("svn1","ato-svn3-sslv3.of.lan");
Strings are immutable so you need to assign the return value to a variable:
string replacement = "ato-svn3-sslv3.of.lan";
url = url.Replace("svn1", replacement);
You can use the string method replace.
url = url.Replace("svn1", urlMod)
I think you need this:
string url = "svn1/dev";
string anotherUrl = "ato-svn3-sslv3.of.lan/svn/dev";
string toBeReplaced = anotherUrl.Split('/')[0];
url = url.Replace("svn1", toBeReplaced);
It uses split method and replace method.

Regular expression (getting number, C#)

Please help me to write Regular expression on C# for getting Int64 value from string:
"NumberLong("634461051992965873")"
my string includes NumberLong part;
so as result must be 634461051992965873
Thank you!)))
string Temp = "Hax00r L33t";
string Output = Regex.Replace(Temp, "[^0-9]", "");
long num = long.Parse(Output);
long.Parse("634461051992965873")
does the job, but you could check long.TryParse too.
String txt = "634461051992965873";
int nbr;
if(Int64.TryParse(txt, out nbr)) {
// text can be converted to Integer
}

Format String as phone number in C#

I have a string value 1233873600 in C# and I have to convert it to 123-387-7300 in C#
Is there any in-built function which will do that in c#?
Cast your string to a long and use the format "{0:### ### ####}";
string.Format("{0:(###) ###-####}", 1112223333);
string phone = "1233873600".Insert(6, "-").Insert(3, "-");
You can use a simple helper method that will take the string, sterilize the input in order to remove spaces or unwanted special characters being used as a separator, and then use the ToString method built-in. If you check for various lengths you can also assure the format comes out as you see fit. For example:
public string FormatPhoneNumber(string phoneNumber)
{
string originalValue = phoneNumber;
phoneNumber= new System.Text.RegularExpressions.Regex(#"\D")
.Replace(phoneNumber, string.Empty);
value = value.TrimStart('1');
if (phoneNumber.Length == 7)
return Convert.ToInt64(value).ToString("###-####");
if (phoneNumber.Length == 9)
return Convert.ToInt64(originalValue).ToString("###-###-####");
if (phoneNumber.Length == 10)
return Convert.ToInt64(value).ToString("###-###-####");
if (phoneNumber.Length > 10)
return Convert.ToInt64(phoneNumber)
.ToString("###-###-#### " + new String('#', (phoneNumber.Length - 10)));
return phoneNumber;
}
I think regex is the best option.
this site is great for finding pre made regex strings.
http://www.regexlib.com/
You might want to use regex for this. The regex for North America phone number looks like this
^(\(?[0-9]{3}\)?)?\-?[0-9]{3}\-?[0-9]{4}$
I guess you can use Regex.Replace method in C#.
String Format didn't work for me, so I did:
string nums = String.Join("", numbers);
return nums.Insert(0, "(").Insert(4, ")").Insert(5, " ").Insert(9, "-");

Categories