I have an InputTextbox that will have text in it such as:
"search google for test"
And this is the code I have at the moment:
String searchRequest = InputTextbox.Text;
searchRequest = searchRequest.SubString(searchRequest.IndexOf("for ") + 4, searchRequest.Length-1);
System.Diagnostics.Process.Start(#"C:\Program Files\Internet Explorer\iexplore.exe", "http://www.google.com.au/search?q=" + searchRequest);
What I am trying to do is search the "InputTextbox.Text" for the word "for" and use anything after it as the search term.
Can someone tell me what I'm doing wrong with this please.
One error is in the SubString. The second parameter is meant to be the length of the substring, not the index of the end of the substring. You need to change this to:
searchRequest.SubString(searchRequest.IndexOf("for ") + 4, searchRequest.Length-1 - (searchRequest.IndexOf("for ") + 4));
If that makes sense.
I would avoid using substring here anyway because it can be quite unpredictable. For example, if "for" is not typed into the textbox, you'll get an error and if two "for"s are typed in, I don't even know what will happen. You should try usin RegExp (http://www.regular-expressions.info/) instead:
String searchRequest = InputTextbox.Text;
searchRequest = new System.Text.RegularExpressions.Regex("(?<=for ?).+$").Match(searchRequest).Value;
System.Diagnostics.Process.Start("http://www.google.com.au/search?q=" + System.Uri.EscapeDataString(searchRequest));
Note that I have removed the "iexplore" bit from the process.start routine. This is ok for people who use internet explorer, but it is best not to specify a browser here so as the default browser can be used instead. Note also that I have used System.Uri.EscapeDataString. This will cover you incase the user enters an ampersand into the search box.
If the error says "StartIndex cannot be less than zero" then there will be probably something wrong here:
searchRequest.Length-1
For example, searchRequest.Length may be zero and you're subtracting 1 from it.
Problem : you are giving complete String Length as second parameter for Substring() function.
Solution : You should provide the substring Length (number of characters to be extracted out of the string) as second Parameter for Substring()
function.
Syntax of Substring() from MSDN
Substring(Int32, Int32) : Retrieves a substring from this instance.
The substring starts at a specified character position and has a
specified length.
Try This:
String searchRequest = "search google for test";
int index = searchRequest.IndexOf("for ") + 4;
searchRequest = searchRequest.Substring(index,searchRequest.Length-index);
System.Diagnostics.Process.Start(#"C:\Program Files\Internet Explorer\iexplore.exe", "http://www.google.com.au/search?q=" + searchRequest);
Related
I'm trying to compare below two strings using c# asp.net core. The motivation is to compare two paths except path parameter (without manually splitting and comparing one by one). Is it possible to do this in single line using any in-build method?
Requested: /api/v1/schedules/S210715001/comments
Original: /api/v1/schedules/{id}/comments
Thanks in advance.
You could create a regex pattern of the original string containing curly brackets and then match against the requested string.
string original = #"/api/v1/schedules/{id}/comments";
string requested = #"/api/v1/schedules/S210715001/comments";
string originalPattern = Regex.Replace(original, #"\{[^\}]*\}", #"\w*");
var isMatch = Regex.Match(requested, $"^{originalPattern}$", RegexOptions.IgnoreCase).Success;
There is a built-in fuction called Path.GetFileName in System.IO allowing you to extract a file name from a whole path.
Here is how to use it:
var original = "/api/v1/schedules/S210715001/comments";
var requested = "api/v1/schedules/{id}/comments";
Console.WriteLine("original: " + Path.GetFileName(original));
Console.WriteLine("requested: " + Path.GetFileName(requested));
output:
original: comments
requested: comments
Note : there are some subtilities on what is considered a directory separator : backslash, forward slash etc. (see here), but I think it's easier to use than regular expressions.
I have an application where I have to provide number of parameters in the format Name:Value
I provide the list of parameters through the Command line arguments value under "Debug" section of the project
So, it look something like that: "MyJobName" "0" "#FullFilePath:C:\MyFile.txt" "#FileType:MyFileType" "#FileDate:20200318" "#FileID:MyAppID"
One parameter is FilePath:C:\FileDir\MyFileTxt.txt
So, when the following logic is applied:
for (int i = 2; i <= args.GetLength(0) - 1; i++)
{
L.Add(args[i].Split(':')[0], args[i].Split(':')[1]);
}
My Parameter looks like that: FilePath:C, ignoring the rest of the path.
The final parameter list that I need to pass to the Stored Procedure should have "Name:Value" format
How can I fix that?
Split lets you pass the maximum array length.
See Split Split(Char[], Int32)
Splits a string into a maximum number of substrings based on the characters
in an array.
You also specify the maximum number of substrings to return.
Sample:
var keyValue = args[i].Split(new char[]{ ':' }, 2);
L.Add(keyValue[0], keyValue[1]);
This way only the first : is taken. The other : that come after it are ignored and will be part of the second item in the array.
But I honestly advise you to use a proper parameter parser, because your approach is very easy to break and very very fragile.
https://github.com/commandlineparser/commandline
Have a look at dragonfruit and Systel.CommandLine
Instead of writing your arguments parser yourself.
It’s a way to have type safe arguments in your main method.
Scott Hanselman has a great blog post about it.
The great part being your XML comments are used to generate a help message.
The moment you use Split, you exclude the delimiter from being a valid character without having to add the extra overloads to it. So if you absolutely must use a colon as your delimiter, you can either use the Split with overload as suggested above, or write extra code to address it;below is how I would parse it.
Of course, a much easier alternative (if possible) would be to change your delimiter to something you know it would never use, something like a pipe or a tilde or a backtick (|, ~, ). Then Split would work cleanly.
"#FullFilePath:C:\MyFile.txt" "#FileType:MyFileType" "#FileDate:20200318" "#FileID:MyAppID"
If your parameters always have the format #ParameterName:ParameterValue, your best bet is to parse the command line args like so:
var argumentsList = new Dictionary<string,object>();
for (int i=2; i < args.Length; i++)
{
int colonIndex = args[i].IndexOf(":");
string parameterName = args[i].Substring(0, colonIndex - 1);
string parameterValue = args[i].Substring(colonIndex + 1);
argumentsList[parameterName] = parameterValue;
}
The scope of your question centers around how to get around the colon, so however you choose to store the parameter values is up to you, I just used the dictionary as an example to help wrap up the code.
This will skip FilePath and give you C:\FileDir\MyFileTxt.txt
string.Join(":", args[i].Split(':').Skip(1));
I'm trying to use a url to post a username back and fourth from another page. My current code (which gives an error "StartIndex cannot be less than zero.".
if (Convert.ToString(Context.Request.QueryString).StartsWith("username"))
{
string username = Convert.ToString(Context.Request.QueryString);
string input = username.Substring(username.LastIndexOf(":"));
txt_username.Text = input;
}
the url looks like 192.168.1.1/p/login.aspx?username:textIwantintxtbox
Obviously just trying to put the last bit into a text box.
You seem to be taking a longer way to get the value you actually want. Since you start with a QueryString, you should just use that.
txt_username.Text = Context.Request.QueryString['username'];
As for your actual error, Substring needs to start from at least index 0, LastIndexOf seems to be returning -1, indicating it hasn't found the colon, probably because get parameters normally use an = instead of a :
I'm trying to get the first occurrence in my substring start point:
string dir = Request.MapPath(Request.ApplicationPath) + "\\App_GlobalResources\\";
foreach (var file in Directory.EnumerateFiles(dir, "*.resx"))
{
ddlResources.Items.Add(new ListItem { Text = file.Substring(firstoccuranceof("."), file.LastIndexOf(".")), Value = file });
}
if I do file.Substring(file.IndexOf("."), file.LastIndexOf(".")) I get an error
To answer your actual question - you can use string.IndexOf to get the first occurrence of a character. Note that you'll need to subtract this value from your LastIndexOf call, since Substring's second parameter is the number of characters to fetch, not a start and end index.
However... Instead of parsing the names, you can just use Path.GetFilenameWithoutExtension to get the filename directly.
First occurence
String.IndexOf('.')
Last occurence
String.LastIndexOf('.')
Use IndexOf and LastIndexOf string methods to get index of first and last occurrence of "search" string. You may use System.IO.Path.GetExtension(), System.IO.Path.GetFileNameWithoutExtension(), and System.IO.Path.GetDirectoryName() methods to parse the path.
For instance,
string file = #"c:\csnet\info.sample.txt";
Console.WriteLine(System.IO.Path.GetDirectoryName(file)); //c:\csnet
Console.WriteLine(System.IO.Path.GetFileName(file)); //info.sample.txt
Console.WriteLine(System.IO.Path.GetFileNameWithoutExtension(file));//info.sample
Console.WriteLine(System.IO.Path.GetExtension(file)); //.txt
file.IndexOf(".")
Should get you the first occurence of ".". Otherwise it will return -1 if not found.
I think that in your particular case you are NOT trying to get IndexOf... Instead you need to use 0 because you are trying to create a key based on filename if understand correctly:
`ddlResources.Items.Add(new ListItem(file.Substring(0, file.LastIndexOf(".")), file ));`
Also, you have '{}' in there as in new ListItem { ... } which is also going to cause a syntax error... Anyhow have a look..
Because the original question is marked with the [regex] tag, I'll provide the following solution, however the best answer for simple parsing of paths using .NET is not by regex.
//extracts "filename" from "filename.resx"
string name = Regex.Match("filename.resx", #"^(.*)\..+?$").Groups[1].Value;
Use an answer that relies on the Path class instead, for simplicity. Other answers contain that info.
Here you go!)
Using a string variable type
int index = str.IndexOf(#"\");
"C:\Users\somebody\Desktop\aFolder\someFile"
https://www.peachpit.com/articles/article.aspx?p=31938&seqNum=12#:~:text=To%20find%20the%20first%20or,string%20you%20are%20searching%20for.
I have a button that when the user clicks it, it must go to a specified URL.
But I have to create my URL out of the values coming from database and most importantly, I need to modify the values coming from database before I make a URL out of it.
Suppose the values from database is
country- France
hotel - Hotel Movenpick
Now first I have to turn the capitals from above values to lowercase, then spaces to '-' sign.
Then i will have to create my URL with these modified values as below.
http://www.travel.com/france/hotel-movenpick
I have never done this before. Please provide me some reference for doing this task. I am coding in c#.
How about:
string fixedCountry = country.ToLower(CultureInfo.InvariantCulture)
.Replace(" ", "-");
string fixedHotel = hotel.ToLower(CultureInfo.InvariantCulture)
.Replace(" ", "-");
string url = "http://www.travel.com/" + fixedCountry + "/" + fixedHotel;
Note that this won't fix up any accented characters or other symbols. It becomes more complicated if you want to do that. It will depend on how much you trust your data to not contain that sort of thing.
If you need to make this any more complicated, or need to do it anywhere else, I suggest you create a "string fixing" method which munges it appropriately, then call it for each of your fields.
EDIT: Removing accented characters is interesting. .NET makes this fairly easy, but I don't know what it will do for your "ae" situation - you may need to special-case that. Try this though, as a starting point:
static string RemoveAccents (string input)
{
string normalized = input.Normalize(NormalizationForm.FormKD);
Encoding removal = Encoding.GetEncoding
(Encoding.ASCII.CodePage,
new EncoderReplacementFallback(""),
new DecoderReplacementFallback(""));
byte[] bytes = removal.GetBytes(normalized);
return Encoding.ASCII.GetString(bytes);
}