Substring IndexOf in c# - c#

I have a string that looks like this: "texthere^D123456_02". But I want my result to be D123456.
this is what i do so far:
if (name.Contains("_"))
{
name = name.Substring(0, name.LastIndexOf('_'));
}
With this I remove at least the _02, however if I try the same way for ^ then I always get back texthere, even when I use name.IndexOf("^")
I also tried only to check for ^, to get at least the result:D123456_02 but still the same result.
I even tried to name.Replace("^" and then use the substring way I used before. But again the result stays the same.
texthere is not always the same length, so .Remove() is out of the question.
What am I doing wrong?
Thanks

When call Substring you should not start from 0, but from the index found:
String name = "texthere^D123456_02";
int indexTo = name.LastIndexOf('_');
if (indexTo < 0)
indexTo = name.Length;
int indexFrom = name.LastIndexOf('^', indexTo - 1);
if (indexFrom >= 0)
name = name.Substring(indexFrom + 1, indexTo - indexFrom - 1);

string s = "texthere^D123456_02";
string result= s.Substring(s.IndexOf("^") + 1);//Remove all before
result = result.Remove(result.IndexOf("_"));//Remove all after

Use the String.Split method :
var split1 = name.Split('^')[1];
var yourText = split1.Split('_')[0];
Or you could use RegExp to achieve basically the same.

Your easiest solution would be to split the string first, and then use your original solution for the second part.
string name = "texthere^D123456_02";
string secondPart = name.Split('^')[1]; // This will be D123456_02
Afterwards you can use the Substring as before.

With Regular Expression
string s = "texthere^D123456_02";
Regex r1 = new Regex(#"\^(.*)_");
MatchCollection mc = r1.Matches(s);
Console.WriteLine("Result is " + mc[0].Groups[1].Value);

An alternative to what's already been suggested is to use regex:
string result = Regex.Match("texthere^D123456_02", #"\^(.*)_").Groups[1].Value; // D123456

use regex.
Regex regex = new Regex(#"\^(.*)_");
Match match = regex.Match(name);
if(match.Success)
{
name= match.Groups[1].Value
}

An easier way would be to use Split
string s = "texthere^D123456_02";
string[] a = s.Split('^', '_');
if (a.Length == 3) // correct
{
}

Well, if you use the same code you posted, it's doing the right thing, you start to retrieve characters from the char 0 and stop when it finds "^", so what you will get is "texthere".
If you want only the value, then use this:
name = name.Substring(0, name.LastIndexOf('_')).Substring(name.IndexOf("^") + 1);
It will first remove whatever is after the "_" and whatever is before "^".

Substring takes a position and a length, so you need to actually figure out where your caret position is and where the underscore is to calculate the length
var name = "texthere^D123456_02";
if(name.Contains('_'))
{
var caretPos = name.IndexOf('^') + 1; // skip ahead
var underscorePos = name.IndexOf('_');
var length = underscorePos - caretPos;
var substring = name.Substring(caretPos, length);
Debug.Print(substring);
};

Try this and let me know how it goes
string inputtext = "texthere^D123456_02";
string pattern = #".+\^([A-Z]+[0-9]+)\_[0-9]+";
string result = Regex.Match(inputtext, pattern).Groups[1].Value;

String name = "texthere^D123456_02"
print name.split('_', '^')[1]
This splits your string at all occurrences of _ and ^ and returns the list of strings after the split. Since the string you need D123456 would be at the 1st index, (i.e. the 2nd position), I have printed out that.

If you are just wanting the "d123456" it's simple with just String.Split() there is no need for anything else. Just define the index you want afterwards. There are overloads on Split() for this very reason.
//...
var source = "texthere^D123456_02";
var result = source.Split(new char[] {'^', '_'}, StringSplitOptions.RemoveEmptyEntries)[1];
Console.WriteLine(result);
//Outputs: "D123456"
Hope this helps.

Related

Replace first occurrence of 0 from string consisting of both numbers and letters

I am trying to remove first 0 from integer part of the string.
IF "CATI-09100" has 0 first in interger part remove it and string would be "CATI-9100". Otherwise no change. I tried using substring. But I need better and efficient way to do it. Also, "CATI-" will be in every string. Any hint will do.
I was thinking on below lines :
strICTOID = Convert.ToString(drData.GetValue(0).Equals(System.DBNull.Value) ? string.Empty : drData.GetValue(0).ToString().Trim());
if (strICTOID.Length > 0)
{
indexICTO = strICTOID.IndexOf("-");
}
Use a simple string replace.
string text = "CATI-09100";
string newText = text.Replace("-0", "-"); // CATI-9100
you can use something like this-
string check = indexICTO.Split('-')[1]; // will split by "-"
if(check[0].Equals("0")) // will check if the charcter after "-" is 0 or not
indexICTO = indexICTO.Replace("-0", "-");
if you want to remove all the zeros at the begining of an integer you can do this:
your_string = Regex.Replace(your_string, #"-0+(\d+)", "$1");
//CATI-009100 --> CATI-9100
//CATI-09100 --> CATI-9100
//CATI-9100 --> CATI-9100
Referencing Replace first occurrence of pattern in a string
var regex = new Regex(Regex.Escape("0"));
var newText = regex.Replace("CATI-09100", "", 1);
This is a rookie way but sure works.
string myString , firstPart,secondPart ;
int firstNumValue;
myString = "CATI-09994";
string[] parts = myString.Split('-');
firstPart = parts[0];
secondPart = parts[1];
firstNumValue = int.Parse(secondPart.Substring(0, 1));
if(firstNumValue == 0){
secondPart = secondPart.Remove(0,1);
}
Console.WriteLine(firstPart+"-"+secondPart);

Remove characters between in c#

I have a string values like this
string strValue = "!return.ObjectV,rgmK12D;1.Value";
In this string how can I remove characters from rgm to ;1?
Below code will remove all the characters from rgm, but I need to remove upto ;1 only
strValue = strValue.Substring(0, strValue.LastIndexOf("rgm"));
Expected Result:
string strValue = "!return.ObjectV,.Value";
Edit 1:
I am trying to remove the above mentioned characters from the below string
Sum ({rgmdaerub;1.Total_Value}, {rgmdaerub;1.Major_Value})
Result
Sum ({rgmdaerub;1.Total_Value}, {Major_Value})
Expected Result
Sum ({Total_Value}, {Major_Value})
A simple solution would be:
strValue = strValue.Substring(0, strValue.LastIndexOf("rgm")) + strValue.Substring(strValue.LastIndexOf(";1") + 2);
EDIT:
According to your edit, it seems you want all occurrences replaced. Also, your expected result has the "." removed as well. To replace all occurrences you can adapt from #Damith's answer:
strValue = Regex.Replace(strValue, "rgm.*?;1\\.", "");
with regex
string strValue = "!return.ObjectV,rgmK12D;1.Value";
var output = Regex.Replace(strValue, #" ?rgm.*?;1", string.Empty);
// !return.ObjectV,.Value
One way is to do it like this:
strValue = strValue.Substring(0, strValue.LastIndexOf("rgm")) +
strValue.Substring(strValue.LastIndexOf(";1"), strValue.Length);
This way you get the first part and the second part then concatenate them together. This will work if you have only one instance of these characters.
You can use something like this. First find "rgm" and ";1" position, then remove characters between these indexes.
int start = strValue.LastIndexOf("rgm");
int end = strValue.LastIndexOf(";1");
string str = strValue.Remove(start, (end-start)+2);
You can use string.IndexOf() and string.Replace()
var i = strValue.IndexOf("rgm");
var j = strValue.IndexOf(";1");
var removePart = strValue.Substring(i, j - i);
strValue.Replace(removePart, string.Empty);

best possible way to get given substring

lets say I have string in format as below:
[val1].[val2].[val3] ...
What is the best way to get the value from the last bracket set [valx] ?
so for given example
[val1].[val2].[val3]
the result would be val3
You have to define best first, best in terms of readability or cpu-cycles?
I assume this is efficient and readable enough:
string values = "[val1].[val2].[val3]";
string lastValue = values.Split('.').Last().Trim('[',']');
or with Substring which can be more efficient, but it's not as safe since you have to handle the case that's there no dot at all.
lastValue = values.Substring(values.LastIndexOf('.') + 1).Trim('[',']');
So you need to check this first:
int indexOflastDot = values.LastIndexOf('.');
if(indexOflastDot >= 0)
{
lastValue = values.Substring(indexOflastDot + 1).Trim('[',']');
}
For a quick solution to your problem (so not structural),
I'd say:
var startIndex = input.LastIndexOf(".["); // getting the last
then using the Substring method
var value = input.Substring(startIndex + 2, input.Length - (startIndex - 2)); // 2 comes from the length of ".[".
then removing the "]" with TrimEnd function
var value = value.TrimEnd(']');
But this is by all means not the only solution, and not structural to apply.. Just one of many answers to your problem.
I think you want to access the valx.
The easiest solution that comes in my mind is this one:
public void Test()
{
var splitted = "[val1].[val2].[val3]".Split('.');
var val3 = splitted[2];
}
You can use following:
string[] myStrings = ("[val1].[val2].[val3]").Split('.');
Now you can access via index. For last you can use myStrings[myStrings.length - 1]
Providing, that none of val1...valN contains '.', '[' or ']' you can use a simple Linq code:
String str = #"[val1].[val2].[val3]";
String[] vals = str.Split('.').Select((x) => x.TrimStart('[').TrimEnd(']')).ToArray();
Or if all you want is the last value:
String str = #"[val1].[val2].[val3]";
String last = str.Split('.').Last().TrimStart('[').TrimEnd(']');
I'm assuming you always need the last brace. I would do it like this:
string input = "[val1].[val2].[val3]";
string[] splittedInput = input.split('.');
string lastBraceSet = splittedInput[splittedInput.length-1];
string result = lastBraceSet.Substring(1, lastBraceSet.Length - 2);
string str = "[val1].[val2].[val3]";
string last = str.Split('.').LastOrDefault();
string result = last.Replace("[", "").Replace("]", "");
string input="[val1].[val2].[val3]";
int startpoint=input.LastIndexOf("[")+1;
string result=input.Substring(startpoint,input.Length-startpoint-1);
I'd use the below regex. One warning is that it won't work if there are unbalanced square brackets after the last pair of brackets. Most of the answers given suffer from that though.
string s = "[val1].[val2].[val3]"
string pattern = #"(?<=\[)[^\]]+(?=\][^\[\]]*$)"
Match m = Regex.Match(s, pattern)
string result;
if (m.Success)
{
result = m.Value;
}
I would use regular expression, as they are the most clear from intention point of view:
string input = "[val1].[val2].[val3] ...";
string match = Regex.Matches(input, #"\[val\d+\]")
.Cast<Match>()
.Select(m => m.Value)
.Last();

C# how to pick out certain part in a string

I have a string in a masked TextBox that looks like this:
123.456.789.abc.def.ghi
"---.---.---.---.---.---" (masked TextBox format when empty, cannot use underscore X( )
Please ignore the value of the characters (they can be duplicated, and not unique as above). How can I pick out part of the string, say "789"? String.Remove() does not work, as it removes everything after the index.
You could use Split in order to separate your values if the . is always contained in your string.
string input = "123.456.789.abc.def";
string[] mySplitString = input.Split('.');
for (int i = 0; i < mySplitString.Length; i++)
{
// Do you search part here
}
Do you mean you want to obtain that part of the string? If so, you could use string.Split
string s = "123.456.789.abc.def.ghi";
var splitString = s.Split('.');
// splitString[2] will return "789"
You could simply use String.Split (if the string is actually what you have shown)
string str = "123.456.789.abc.def.ghi";
string[] parts = str.Split('.');
string third = parts.ElementAtOrDefault(2); // zero based index
if(third != null)
Console.Write(third);
I've just used Enumerable.ElementAtOrDefault because it returns null instead of an exception if there's no such index in the collection(It falls back to parts[2]).
Finding a string:
string str="123.456.789.abc.def.ghi";
int i = str.IndexOf("789");
string subStr = str.Substring(i,3);
Replacing the substring:
str = str.Replace("789","").Replace("..",".");
Regex:
str = Regex.Replace(str,"789","");
The regex can give you a lot of flexibility finding things with minimum code, the drawback is it may be difficult to write them
If you know the index of where your substring begins and the length that it will be, you can use String.Substring(). This will give you the substring:
String myString = "123.456.789";
// looking for "789", which starts at index 8 and is length 3
String smallString = myString.Substring(8, 3);
If you are trying to remove a specific part of the string, use String.Replace():
String myString = "123.456.789";
String smallString = myString.Replace("789", "");
var newstr = new String(str.where(c => "789")).tostring();..i guess this would work or you can use sumthng like this
Try using Replace.
String.Replace("789", "")

Cut a text on a string when '.' is found in the text [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Remove characters after specific character in string, then remove substring?
I have a string variabel that contains a text like this:
"Hello My name is B and I love soccer. I live in California."
I want to cut the text after the first '.' so the text displays
"Hello My name is B and I love soccer."
How can I do it in the simpliest way?
I tried:
Char Mychar = '.';
Stringvariabel.trimstart(Mychar);
But I guess it's wrong.
Char Mychar = '.';
Stringvariabel = Stringvariabel.Split(Mychar).First() + Mychar.toString();
If you're only interested in the first sentence, then just grab a substring starting at the beginning and ending at the '.'.
Stringvariabel.Substring(0, Stringvariabel.IndexOf('.') + 1);
You can use string.Split to get the result:
string input = "Hello My name is B and I love soccer. I live in California. ";
string result = string.Format("{0}.", input.Split('.').First());
Make use of IndexOf function will do work for you..
string input = "Hello My name is B and I love soccer. I live in California. ";
int i = input .IndexOf('.');
string result = s.Substring(0,i+1);
One convenient way is to use string.Split and ask for just the first part:
var firstPart = input.Split(new[] { '.' }, 1).First();
This is quite efficient because it won't continue processing the string after the first dot, but it will remove the dot (if it exists) and you will not be able to tell if there was a dot in the first place.
The other option is string.IndexOf and a conditional:
var index = input.IndexOf(".");
if (index != -1) {
input = input.SubString(0, index);
}
TrimStart removes characters from the start of a string that are in the list you give it. It would only remove a . if it appears at the very start.
You can find the first . and take a substring up to that point:
stringVar.Substring(0, stringVar.IndexOf('.') + 1);
You can do something like below
stringVariable.Split('.')[0]
or
stringVariable.SubString(0, stringVariable.IndexOf(".") + 1)
Hope this Helps!!
The simplest way would be to take the substring up until the first occurrence of the character.
public string TrimAtFirstChar(string s, char c)
{
int index = s.IndexOf(c);
if(index == -1) //there is no '.' in the string
return s;
return s.Substring(0, index)
}
Alternately, to avoid worrying about the case where there is no '.', you could use stringvariable.Split('.')[0].
Take a look at the String.Split method.
var myString = "Hello My name is B and I love soccer. I live in California. ";
var firstPart = myString.Split('.')[0];
var splitLine = yourString.Split('.');
if (splitLine != null && splitLine.Count > 0)
return splitLine[0];
Without split, only using Substring and IndexOf (which is more efficient when the text is very large):
int index = text.IndexOf(".") + 1;
String result = text;
if(index > 0)
result = text.Substring(0, index);
http://ideone.com/HL6GwN
Please be aware that String.Split() can have an impact, cause you create an array that contains all substrings delimited by the given separator, but you are only interested in the first occurence. So using IndexOf() and Substring() makes much more sense.
string input = "Hello My name is B and I love soccer. I live in California. ";
var index = input.IndexOf(".");
var result = index > 0
? input.Substring(0, index)
: input;
variablename.Substring(0, variablename.IndexOf('.') + 1);

Categories

Resources