substring from specific point of the string(from reverse side ) - c#

I wanted to substring from special point.
abcdef.png
I want
.png
Here i tried
string str = "abcdef.png";
str = str.Substring(0, str.Length - 4);
but then only shows the abcdef only BUT i want .png part

Just use the overload which takes a single parameter - the start point:
str = str.Substring(str.Length - 4);
Or better, use a method designed to get the extension of a filename - Path.GetExtension:
string extension = Path.GetExtension(str);

You can use Path.GetExtension method instead of substring.
string str = "abcdef.png";
string ext = Path.GetExtension(str); // .png

It seems you're dealing with file names, Use Path.GetExtension method for this purpose.

You need to pass str.Length - 4 as the first (and only) parameter, not as the second parameter:
str = str.Substring(str.Length - 4);
The way your code had it, you got a substring starting at zero, and containing str.Length - 4 characters.
If you want to take just the dot and the extension, use
str = str.Substring(str.LastIndexOf('.'));
expression.

If you want the extension of a filename use Path.GetExtension(str). Much easier.
http://msdn.microsoft.com/en-us/library/system.io.path.getextension(v=vs.110).aspx

try below code it will return the extension of file.
string extension = Path.GetExtension(str);

Related

Get arguments and file name from specific path

I'm trying to extract argument and file name from path like below:
C:\Users\user\Desktop\foo.exe foo://action/bar
I tried to use Path.GetFileName but since argument contains directory separators, it returns bar instead of foo.exe
Is there any way to get argument and file name?
You can get the command line argument from the string [] args passed to the Main method.
Or you can use the static method Environment.GetCommandLineArgs https://msdn.microsoft.com/en-us/library/system.environment.getcommandlineargs(v=vs.110).aspx
Use LastIndexOf to reverse-search the string for the backslash, then Substring to grab everything beyond that:
int i = path.LastIndexOf(#"\");
return (i > -1 && i < path.Length) ? path.Substring(i + 1) : string.Empty;
If you need to separate the filename and argument, use IndexOf to look for the space or Split the result on the space character.

Why My string . Find is not avalible

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.

Remove last characters from a string in C#. An elegant way?

I have a numeric string like this 2223,00. I would like to transform it to 2223. This is: without the information after the ",". Assume that there will be only two decimals after the ",".
I did:
str = str.Remove(str.Length - 3, 3);
Is there a more elegant solution? Maybe using another function? -I donĀ“t like putting explicit numbers-
You can actually just use the Remove overload that takes one parameter:
str = str.Remove(str.Length - 3);
However, if you're trying to avoid hard coding the length, you can use:
str = str.Remove(str.IndexOf(','));
Perhaps this:
str = str.Split(",").First();
This will return to you a string excluding everything after the comma
str = str.Substring(0, str.IndexOf(','));
Of course, this assumes your string actually has a comma with decimals. The above code will fail if it doesn't. You'd want to do more checks:
commaPos = str.IndexOf(',');
if(commaPos != -1)
str = str.Substring(0, commaPos)
I'm assuming you're working with a string to begin with. Ideally, if you're working with a number to begin with, like a float or double, you could just cast it to an int, then do myInt.ToString() like:
myInt = (int)double.Parse(myString)
This parses the double using the current culture (here in the US, we use . for decimal points). However, this again assumes that your input string is can be parsed.
String.Format("{0:0}", 123.4567); // "123"
If your initial value is a decimal into a string, you will need to convert
String.Format("{0:0}", double.Parse("3.5", CultureInfo.InvariantCulture)) //3.5
In this example, I choose Invariant culture but you could use the one you want.
I prefer using the Formatting function because you never know if the decimal may contain 2 or 3 leading number in the future.
Edit: You can also use Truncate to remove all after the , or .
Console.WriteLine(Decimal.Truncate(Convert.ToDecimal("3,5")));
Use:
public static class StringExtensions
{
/// <summary>
/// Cut End. "12".SubstringFromEnd(1) -> "1"
/// </summary>
public static string SubstringFromEnd(this string value, int startindex)
{
if (string.IsNullOrEmpty(value)) return value;
return value.Substring(0, value.Length - startindex);
}
}
I prefer an extension method here for two reasons:
I can chain it with Substring.
Example: f1.Substring(directorypathLength).SubstringFromEnd(1)
Speed.
You could use LastIndexOf and Substring combined to get all characters to the left of the last index of the comma within the sting.
string var = var.Substring(0, var.LastIndexOf(','));
You can use TrimEnd. It's efficient as well and looks clean.
"Name,".TrimEnd(',');
Try the following. It worked for me:
str = str.Split(',').Last();
Since C# 8.0 it has been possible to do this with a range operator.
string textValue = "2223,00";
textValue = textValue[0..^3];
Console.WriteLine(textValue);
This would output the string 2223.
The 0 says that it should start from the zeroth position in the string
The .. says that it should take the range between the operands on either side
The ^ says that it should take the operand relative to the end of the sequence
The 3 says that it should end from the third position in the string
Use lastIndexOf. Like:
string var = var.lastIndexOf(',');

how to extract substring from a undefined length of string?

Substring these string:-
1. ZZ111122
2. ZZZZ222111
3. ZZZZZZZ333
4. ZZZ111333
I have these kind of strings. This value is always starting with Z. And after Z its always either 1 or 2 or 3. But i dont know the number of Zs in the string. So how can i extract all Z from the string
I don't know if I understood right. If you have "ZZZZ222111" and want only "222111", do it:
string test = "ZZZZ222111";
test = test.Substring(test.LastIndexOf("Z") + 1);
If you want only "ZZZZ", do it:
string test = "ZZZZ222111";
test = test.Substring(0, test.LastIndexOf("Z"));
Both ways are very simple. No need of loops or regular expressions.
Sounds like you're going to want to use regular expressions for this.
Use String.Trim function:
ZeroZValue = stringValue.Trim('Z');
String test = "ZZ111122";
String zOnly = test.Substring(0, test.IndexOfAny("123".ToCharArray()));
Take advantage of IndexOfAny(). I am assuming you want only Z's left over ("extract all Z from the string").
This is not difficult. I recommend processing the text line by line.
You can loop the string character by character. You can use regular expressions. Or you could use my sscanf() replacement class for C#.
int start = someString.IndexOf("Z");
int end = someString.LastIndexOf("Z");
someString.Substring(start , end - start);

Delete String Elements

How to delete the last element of a string.
If 'globe'
is the value given by user, how to store it as 'glob'.
That is excluding last element.
You can use the string.Substring() method. Pass in the start of the string (0) and the length you want (Length - 1).
string globe = "globe";
string glob = globe.Substring(0, globe.Length - 1);
The resulting string glob will now be "glob".
Use the string.Substring overload that takes two arguments, startIndex and length:
s = s.Substring(0, s.Length - 1)
There are many ways. For example:
You can use the Substring method:
string first = original.Substring(0, original.Length - 1);
You can use the Remove method:
string first = original.Remove(original.Length - 1);
You can use the Take method:
string first = new String(original.Take(original.Length - 1).ToArray());
You can use the TakeWhile method:
string first = new String(original.TakeWhile((c,i) => i < original.Length - 1).ToArray());
just use the Substring method. You will want to use 0 for the starting value and s.Length - 1 for the amount of the string to be used (assuming s is the name of your string).

Categories