Remove characters between in c# - 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);

Related

Delete first element of a string using a method,C#

Im am very new in C#.
How i can delete first element of a string using a method,i find something on this site but didnt work so help me please.
For example
string newString = oldString.Substring(1);
If you want to remove the first word from your string you could use LINQ Skip combined with String.Split and String.Join:
string str = "How are you?";
string result = string.Join(" ", str.Split().Skip(1));//"are you?"
If you want only to remove the first letter you could use String.Substring:
string result = str.Substring(1);//"ow are you?";
Or if you want a LINQ solution you could use LINQ Skip:
string result = new string(str.Skip(1).ToArray());//"ow are you?";
Another solution is to use Remove method:
string myStr = "dsafavveebvesf";
//remove one character at position 0 - at the beginning
myStr = myStr.Remove(0, 1);
If you are not aware of Linq, you can simply use for loop to do the same.
Here you can use Split method of string.
string amit = "my name is amit";
string restultStr = string.Empty;
//taking all words in sentence in one array
string [] strWords = amit.Split();
//as we start this with 1 instead of 0, it will ignore first word
for (int i = 1; i < strWords.Length; i++)
{
restultStr += strWords[i] + " ";
}
EDIT
Now I see there are two onions here, removing first letter of the string and removing first word.
Above answer was to remove first word. if you want to just remove first letter, you can always do as suggested.
string amit = "my name is amit";
string restultStr = amit.Substring(1);

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

Substring IndexOf in 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.

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

How do I add a comma after the fourth character in a sentence?

I know nothing of C# so I'm hoping somebody here can help. So my question is how would I add a "," after the fourth character in a string. Something like:
Hell,o?
You can use .Insert():
string test = "Hello";
test = test.Insert(4, ",");
You should check if the string is long enough though like so:
if (test.Length > 4) {
test = test.Insert(4, ",");
}
You need to use String.Insert and give the number 4 as parameter (since the first char is on place 0)
string s = "hello";
s = s.Insert(4, ",");
Use String.Insert.
E.g. myString.Insert(4, ",");
String.Insert is the answer:
string test1 = "Hello";
string test2 = test1.Insert(4, ",");
http://msdn.microsoft.com/en-us/library/system.string.insert.aspx
var str ="Hello";
var finalString = string.Format("{0},{1}",str.Substring(0,4),str.Substring(4));
Firstly, strings are immutable so you have to create a new string
var sampleString = "Testing";
var resultString = sampleString.Insert(3, ",);
resultString is "Test,ing"
Use below code
String str = "Hello";
str = str.Substring(0, 4) + "," + str.Substring(4, str.Length - 4);
I'm gonna Propose an alternative to insert, this way it'll be possible for future users to use for editing a longer string and put in values at different intervals eg.
"hello my name is Anders"
becomes
"hell,o my, nam,e is, And,ers"
A string in C# is basically an array of chars, so you could loop through it and when you reach the fourth loop you could insert your ,
something like this
string hello="hello";
string newvar ="";
foreach(int i =0;i<hello.length;i++)
{
if(i==4)
newvar+=",";
newvar+=hello[i];
}
if you want it to be each fourth space you can check if 0%=4/i
you can also use Substring split it up into multiple pieces put in your "," and put it back together, I suggest you take a look at the documentation for the string class at Microsofts homepage

Categories

Resources