I want to find if a string has "/" in front of it, in my code I get indexof of the string and find out if the character before it has anything, which works but how do I find if it actually is forward slash. here is my code:
string test = "/images/";
if (test.IndexOf(#"images/") - 1 == -1)
{
}
EDIT
Some of my strings may have full url and some may be as above and some may not have / at all hence using index of
Do you mean:
if (test.StartsWith("/"))
? (It's not clear what your sample code is trying to achieve.)
Note that "/" is a forward-slash, not a backslash - and you don't need the verbatim string literal in your case, given that the string doesn't contain any backslashes or line breaks.
EDIT: Your question isn't clear, but I suspect you want something like:
int index = test.IndexOf(targetString);
if (index > 0 && test[index - 1] == '/')
{
// There's a leading forward slash. Deal with it appropriately
}
You can use Method StartsWith():
if(test.StartsWith("/"))
{
}
if (test.StartsWith("images") ||
test.IndexOf("/images") > -1 ||
test.IndexOf("\\images") > -1)
Too many good answers :)
Anyway, I meant to say the following:
string str = "/\images\///";
Match matchfirstFwdSlash = Regex.Match(str, "^[\\/]", RegexOptions.IgnoreCase);
if (matchfirstFwdSlash.Success)
{MessageBox .Show ("Success","Success");}
else
{MessageBox .Show ("Oops","Oops");}
//You can find this way
string test = "/Images/";
string a = test.Split('/')[0];
if (a=="")
{
}
Related
I'm working on an application to manage filenames of downloaded TV Shows. Basically it will search the directory and clean up the filenames, removing things like full stops and replacing them with spaces and getting rid of the descriptions at the end of the filename after the easily recognizable pattern of, for eg., S01E13. (.1080p.BluRay.x264-ROVERS)
What I want to do is to make a regex expression for use in C# to just extract whatever is before the SnnEnn including itself (where n is any whole positive integer).
But, i don't know much regex to get me going
For example, if I had the filename TV.Show.S01E01.1080p.BluRay.x264-ROVERS, the query would only get TV.Show.S01E01, irrespective of how many words are before the pattern, so it could be TV.Show.On.ABC.S01E01 and it would still work.
Thanks for any help :)
Try this
string input = "TV.Show.S01E01.1080p.BluRay.x264-ROVERS";
string pattern = #"(?'pattern'^.*\d\d[A-Z]\d\d)";
string results = Regex.Match(input, pattern).Groups["pattern"].Value;
There is more obvious way without regex:
string GetNameByPattern(string s)
{
const string pattern_length = 6; //SnnEnn
for (int i = 0; i < s.Length - pattern_length; i++)
{
string part = s.SubString(i, pattern_length);
if (part[0] == 'S' && part[3] == 'N') //candidat
if (Char.IsDigit(part[1]) && Char.IsDigit(part[2]) && Char.IsDigit(part[4]) && Char.IsDigit(part[5]))
return s.SubString(0, i + pattern_length);
}
return "";
}
I use WinForms c#.I have string value like below,
string Something = "1,5,12,34,";
I need to remove last comma in a string. So How can i delete it ?
Try string.TrimEnd():
Something = Something.TrimEnd(',');
King King's answer is of course correct, and Tim Schmelter's comment is also good suggestion in your case.
But if you really want to remove the last comma in a string, you should find the index of the last comma and remove it like this:
string s = "1,5,12,34,12345";
int index = s.LastIndexOf(',');
Console.WriteLine(s.Remove(index, 1));
Output will be:
1,5,12,3412345
Here is a demonstration.
It is unlikely that you want this way but I want to point it out. And remember, the String.Remove method doesn't remove any characters in the original string, it returns new string.
Try string.Remove();
string str = "1,5,12,34,";
string removecomma = str.Remove(str.Length-1);
MessageBox.Show(removecomma);
The TrimEnd method takes an input character array and not a string.
The code below from Dot Net Perls, shows a more efficient example of how to perform the same functionality as TrimEnd.
static string TrimTrailingChars(string value)
{
int removeLength = 0;
for (int i = value.Length - 1; i >= 0; i--)
{
char let = value[i];
if (let == '?' || let == '!' || let == '.')
{
removeLength++;
}
else
{
break;
}
}
if (removeLength > 0)
{
return value.Substring(0, value.Length - removeLength);
}
return value;
}
Dim psValue As String = "1,5,12,34,123,12"
psValue = psValue.Substring(0, psValue.LastIndexOf(","))
output:
1,5,12,34,123
Try below
Something..TrimEnd(",".ToCharArray());
Or you can convert it into Char Array first by:
string Something = "1,5,12,34,";
char[] SomeGoodThing=Something.ToCharArray[];
Now you have each character indexed:
SomeGoodThing[0] -> '1'
SomeGoodThing[1] -> ','
Play around it
When you have spaces at the end. you can use beliow.
ProcessStr = ProcessStr.Replace(" ", "");
Emails = ProcessStr.TrimEnd(';');
Try this,
string Something1= Something.Substring(0, Something.Length - 1 );
I'm woefully attempting a programming assignment. I'm not looking for a "this is how you do this" but more of a "what am I doing wrong?"
I'm attempting to capitalize the start of each sentence from a string input. So for example the string "Hello. my name is john. i like to ride bikes." I would modify the string and return it with capitals for example: "Hello. My name is john. I like to ride bikes." My logic seems a bit flawed and I'm very lost.
What I have so far below. Basically all I'm doing is testing for a punctuation signifying the end of a sentence. And then trying to replace the character. Also testing if it's the at the end of the string as to not create IndexOutOfRange exceptions. Although, that's all I've been getting :(
private string SentenceCapitalizer(string input)
{
for (int i = 0; i < input.Length; i++)
{
if (input[i] == '.' || input[i] == '!' || input[i] == '?')
{
if (!(input[i] == input.Length))
{
input.Replace(input[i + 2], char.ToUpper(input[i + 2]));
}
}
}
return input;
}
Any help is greatly appreciated. I'm just learning C# so the most basic of help would be of service. I don't know much :P
Instead of
if (!(input[i + 2] >= input.Length))
It should be
if (!(i + 2 >= input.Length))
You are comparing indices, not characters
You are checking if your current index is less than or equal to the length of the string and then attempting to alter an index 2 further along
if (!(input[i] == input.Length))
{
input.Replace(input[i + 2], char.ToUpper(input[i + 2]));
}
Should be changed to
if (!((i + 2) >= input.Length))
{
input.Replace(input[i + 2], char.ToUpper(input[i + 2]));
}
This will check that there is a value 2 places after a punctuation mark. Also make use of >= rather than == since you're jumping 2 you might end up going over the length of the array where == still returns false but there is no index.
Strings are immutable, you can't do:
var str = "123";
str.Replace('1', '2');
You have to do:
var str = "123";
str = str.Replace('1', '2');
Ok, others have provided you with some pointers to stop the obvious errors, but I'll try to give you some thoughts on how to best implement this.
It is worth thinking about this as a 3-step process
Tokenize the string into sentences
Ensure that the first character of each token is uppercase
reconstruct the string by joining the tokens back together
(1) I'll leave to your imagination, but the idea is to end up with an array of strings with each element representing a "sentence" according to your requirement
(2) Is pretty much as simple as
// Upercase character 0, and join it to everything from character 1 onwards
var fixedToken = token[0].ToUpper(CultureInfo.CurrentCulture)
+ token.Substring(1);
(3) Is also simple
// reconstruct string by joining all tokens with a space
var reconstructed = String.Join(" ",tokens);
If I have the following string:
/lorem/ipsum/dolor
and I want this to become:
/lorem/ipsum
What is the short-hand way of removing the last forward slash, and all characters following it?
I know how I can do this by spliting the string into a List<> and removing the last item, and then joining, but is there a shorter way of writing this?
My question is not URL specific.
You can use Substring() and LastIndexOf():
str = str.Substring(0, str.LastIndexOf('/'));
EDIT (suggested comment)
To prevent any issues when the string may not contain a /, you could use something like:
int lastSlash = str.LastIndexOf('/');
str = (lastSlash > -1) ? str.Substring(0, lastSlash) : str;
Storing the position in a temp-variable would prevent the need to call .LastIndexOf('/') twice, but it could be dropped in favor of a one-line solution instead.
If there is '/' at the end of the url, remove it.
If not; just return the original one.
var url = this.Request.RequestUri.ToString();
url = url.EndsWith("/") ? url.Substring(0, url.Length - 1) : url;
url += #"/mycontroller";
You can do something like str.Remove(str.LastIndexOf("/")), but there is no built-in method to do what you want.
Edit: you could also use the Uri object to traverse directories, although it does not give exactly what you want:
Uri baseUri = new Uri("http://domain.com/lorem/ipsum/dolor");
Uri myUri = new Uri(baseUri, ".");
// myUri now contains http://domain.com/lorem/ipsum/
One simple way would be
String s = "domain.com/lorem/ipsum/dolor";
s = s.Substring(0, s.LastIndexOf('/'));
Console.WriteLine(s);
Another maybe
String s = "domain.com/lorem/ipsum/dolor";
s = s.TrimEnd('/');
Console.WriteLine(s);
You can use the regex /[^/]*$ and replace with the empty string:
var fixed = new Regex("/[^/]*$").Replace("domain.com/lorem/ipsum/dolor", "")
But it's probably overkill here. #newfurniturey's answer of Substring with LastIndexOf is probably best.
I like to create a String Extension for stuff like this:
/// <summary>
/// Returns with suffix removed, if present
/// </summary>
public static string TrimIfEndsWith(
this string value,
string suffix)
{
return
value.EndsWith(suffix) ?
value.Substring(0, value.Length - suffix.Length) :
value;
}
You can then use like this:
var myString = "/lorem/ipsum/dolor";
myStringClean = myString.TrimIfEndsWith("/dolor");
You now have a re-usable extension across all of your projects that can be used to remove one trailing character or multiple.
using System.IO;
mystring.TrimEnd(Path.AltDirectorySeparatorChar); // To remove "/"
mystring.TrimEnd(Path.DirectorySeparatorChar); // To remove "\"
while (input.Last() == '/' || input.Last() == '\\')
{
input = input.Substring(0, input.Length - 1);
}
Thank you #Curt for your question.
I slightly improved #newfurniturey's code, and here is my version.
if(str.Contains('/')){
str = str.Substring(0, str.LastIndexOf('/'));
}
I'm way late to the party, but if you're using C# 8.0+, another clean approach would be to use the range operator:
if (urlStr.EndsWith("/")) urlStr = urlStr[..^1];
If you're curious as to how this works, take a look at the spec for ranges in C#:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/ranges
tldr; urlStr[..^1] roughly translates to something along the lines of "Give me a substring comprised of the characters contained within the range of index 0 to whatever index is 1 away from the last index.".
In other words, it's similar to...
urlStr.Substring(0, urlStr.Length-1)
What would be the best way and more idiomatic to break a string into two at the place of the last dot? Basically separating the extension from the rest of a path in a file path or URL. So far what I'm doing is Split(".") and then String.Join(".") of everything but the last part. Sounds like using a bazooka to kill flies.
If you want performance, something like:
string s = "a.b.c.d";
int i = s.LastIndexOf('.');
string lhs = i < 0 ? s : s.Substring(0,i),
rhs = i < 0 ? "" : s.Substring(i+1);
You could use Path.GetFilenameWithoutExtension()
or if that won't work for you:
int idx = filename.LastIndexOf('.');
if (idx >= 0)
filename = filename.Substring(0,idx);
To get the path without the extension, use
System.IO.Path.GetFileNameWithoutExtension(fileName)
and to get the extenstion (including the dot), use
Path.GetExtension(fileName)
EDIT:
Unfortunately GetFileNameWithoutExtension strips off the leading path, so instead you could use:
if (path == null)
{
return null;
}
int length = path.LastIndexOf('.');
if (length == -1)
{
return path;
}
return path.Substring(0, length);
The string method LastIndexOf maybe of some use to you here.
But the Path or FileInfo operators will be better suited for filename based operations.
I think what you're really looking for is Path.GetFileNameWithoutExtension Method (System.IO) but just for the heck of it:
string input = "foo.bar.foobar";
int lastDotPosition = input.LastIndexOf('.');
if (lastDotPosition == -1)
{
Console.WriteLine("No dot found");
}
else if (lastDotPosition == input.Length - 1)
{
Console.WriteLine("Last dot found at the very end");
}
else
{
string firstPart = input.Substring(0, lastDotPosition);
string lastPart = input.Substring(lastDotPosition + 1);
Console.WriteLine(firstPart);
Console.WriteLine(lastPart);
}
Path.GetExtension() should help you.
What about using the LastIndexOf method which returns the last found position of a character. Then you can use Substring to extract what you want.
String.LastIndexOf will return you the position of the dot if it ever exists in the string. You can then String.Substring methods to split the string.
You can use string's method
LastIndexOf and substring to acomplish the task.