Delete first element of a string using a method,C# - 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);

Related

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

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.

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

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