Why My string . Find is not avalible - c#

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.

Related

Split string with plus sign as a delimiter

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

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

Fixed string Regular Expression C#

Hi all I want to know something regarding to fixed-string in regular expression.
How to represent a fixed-string, regardless of special characters or alphanumeric in C#?
For eg; have a look at the following string:
infinity.world.uk/Members/namelist.aspx?ID=-1&fid=X
The entire string before X will be fixed-string (ie; the whole sentence will appear the same) BUT only X will be the decimal variable.
What I want is that I want to append decimal number X to the fixed string. How to express that in terms of C# regular expression.
Appreciate your help
string fulltext = "inifinity.world.uk/Members/namelist.aspx?ID=-1&fid=" + 10;
if you need to modify existing url, dont use regex, string.Format or string.Replace you get problem with encoding of arguments
Use Uri and HttpUtility instead:
var url = new Uri("http://infinity.world.uk/Members/namelist.aspx?ID=-1&fid=X");
var query = HttpUtility.ParseQueryString(url.Query);
query["fid"] = 10.ToString();
var newUrl = url.GetLeftPart(UriPartial.Path) + "?" + query;
result: http://infinity.world.uk/Members/namelist.aspx?ID=-1&fid=10
for example, using query["fid"] = "%".ToString(); you correctly generate http://infinity.world.uk/Members/namelist.aspx?ID=-1&fid=%25
demo: https://dotnetfiddle.net/zZ9Y1h
String.Format is one way of replacing token values in a string, if that's what you want. In the example below, the {0} is a token, and String.Format takes the fixedString and replaces the token with the value of myDecimal.
string fixedString = "infinity.world.uk/Members/namelist.aspx?ID=-1&fid={0}";
decimal myDecimal = 1.5d;
string myResultString = string.Format(fixedString, myDecimal.ToString());

Extract strings from string

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

Categories