I know the remove method is used like this:
string MyString = "Hello Beautiful Magic World";
Console.WriteLine(MyString.Remove(5,10));
// The example displays the following output:
// Hello Magic World
I want to keep the 5 characters at the end of the string ("World" in our example) constant and remove the previous 5 characters.
But I don't have the slightest idea how to do it. I tried like this: Unfortunately it did not.
MyString.Substring(0, MyString.Length - 10 - 5);
The following will find the word "Magic" and remove it:
string stringToRemove = myString.Remove(myString.Length - 11, 6);
Related
If I copy " BOB3 27QK DEPM PJ7J T25G SJZI CJA5 BO5O|123456 " and I want to pass it to my text box, and get only the last 6 digits number in my text box, How to do in c#?
Using .Split would look like this:
string myString = "BOB3 27QK DEPM PJ7J T25G SJZI CJA5 BO5O|123456";
char[] mySplitChars = { '|' };
string[] myArray = myString.Split(mySplitChars);
Console.WriteLine(myArray[1]);
Using .Substring would look like this:
Console.WriteLine(myString.Substring(myString.Length - 6));
The latter is probably preferred because it is shorter and it does not rely on the "|" character being present. The former would be preferred if the "|" is always present but the number of characters at the end can change.
How are you passing it your text box? If it's just getting the last n characters:
refer to this answer
I'm currently trying to strip a string of data that is may contain the hyphen symbol.
E.g. Basic logic:
string stringin = "test - 9894"; OR Data could be == "test";
if (string contains a hyphen "-"){
Strip stringin;
output would be "test" deleting from the hyphen.
}
Console.WriteLine(stringin);
The current C# code i'm trying to get to work is shown below:
string Details = "hsh4a - 8989";
var regexItem = new Regex("^[^-]*-?[^-]*$");
string stringin;
stringin = Details.ToString();
if (regexItem.IsMatch(stringin)) {
stringin = stringin.Substring(0, stringin.IndexOf("-") - 1); //Strip from the ending chars and - once - is hit.
}
Details = stringin;
Console.WriteLine(Details);
But pulls in an Error when the string does not contain any hyphen's.
How about just doing this?
stringin.Split('-')[0].Trim();
You could even specify the maximum number of substrings using overloaded Split constructor.
stringin.Split('-', 1)[0].Trim();
Your regex is asking for "zero or one repetition of -", which means that it matches even if your input does NOT contain a hyphen. Thereafter you do this
stringin.Substring(0, stringin.IndexOf("-") - 1)
Which gives an index out of range exception (There is no hyphen to find).
Make a simple change to your regex and it works with or without - ask for "one or more hyphens":
var regexItem = new Regex("^[^-]*-+[^-]*$");
here -------------------------^
It seems that you want the (sub)string starting from the dash ('-') if original one contains '-' or the original string if doesn't have dash.
If it's your case:
String Details = "hsh4a - 8989";
Details = Details.Substring(Details.IndexOf('-') + 1);
I wouldn't use regex for this case if I were you, it makes the solution much more complex than it can be.
For string I am sure will have no more than a couple of dashes I would use this code, because it is one liner and very simple:
string str= entryString.Split(new [] {'-'}, StringSplitOptions.RemoveEmptyEntries)[0];
If you know that a string might contain high amount of dashes, it is not recommended to use this approach - it will create high amount of different strings, although you are looking just for the first one. So, the solution would look like something like this code:
int firstDashIndex = entryString.IndexOf("-");
string str = firstDashIndex > -1? entryString.Substring(0, firstDashIndex) : entryString;
you don't need a regex for this. A simple IndexOf function will give you the index of the hyphen, then you can clean it up from there.
This is also a great place to start writing unit tests as well. They are very good for stuff like this.
Here's what the code could look like :
string inputString = "ho-something";
string outPutString = inputString;
var hyphenIndex = inputString.IndexOf('-');
if (hyphenIndex > -1)
{
outPutString = inputString.Substring(0, hyphenIndex);
}
return outPutString;
I have got a line in a lisbox that i need so i can print out my receipt for the end of my 12 grade project im doing.
Example of my line :"cha1 Adidas Stan Smith White 1 2" (its padded).
Now what i want to do is isolate like cha1, Adidas stan Smith White,1,2 to add to my Microsoft Access Database, i somehow managed to do it with substring but i screwed up my code and now i cant do it , can somebody help me please ?
My code ,that used to work , looks like this :
foreach (string item in lstpreview.Items)
{
//create the string to print on the reciept
string nomeproduto = item;
float quantidade = float.Parse(item.Substring(item.Length -5, 5));
float precounitario = float.Parse(item.Substring(item.Length - 5, 5));
string totalproduto = item.Substring(item.Length - 6, 6);
txt1.Text = Convert.ToString(quantidade);
txt2.Text = Convert.ToString(precounitario);
//MessageBox.Show(item.Substring(item.Length - 5, 5) + "PROD TOTAL: " + totalproduto);
//float totalprice = 0.00f;
}
You say that the line is padded, but do not give any details. If you know that the first field is always the first 4 characters of the line, you can isolate it with string.Substring:
string field1 = line.Substring(0, 4);
and similarly for the other fields.
P.S. Please edit your post and remove the swear word.
Edit after parsing code added
I don't understand your comment, what is "your negative value"? Run the code in the debugger and find which line causes the error. Please post the exact error message.
Is there a reason for converting the substring to a float and then back to a string? I can imagine that you might want to validate that the field is numeric, but then you would be better to use TryParse.
Your second comment is helpful. The last 5 characters of the line are not all numeric, that's the problem.
Done it with this snippet of code together with a for each loop.
string[] caracteresnastring = item.Split(new char[] { ',' }.ToArray());
string code = caracteresnastring[0];
string name = caracteresnastring[1];
string price = caracteresnastring[2];
string quantity = caracteresnastring[3];
I can't seem to wrap my head around this. How can this become:
string.Format(#"https://www.dropbox.com/s/{0}/{1}?dl=1", dl[rndIndex], rndIndex);
this:
/3?dl=1/www.dropbox.com/s/s8ghw2mvld2jg0l
It's like taking the part after {0} ,shifts it to the front and overrides the existing string...
Does anyone know what's going on here?
This is the entire code (pseudo):
string[] dl = new string[] { "...", "...", "..." };
int rndIndex = rnd.Next(0, dl.Length);
Console.WriteLine(string.Format(#"https://www.dropbox.com/s/{0}/{1}?dl=1", dl[rndIndex], rndIndex));
There's nothing wrong with dl[] and rndIndex, checked both of them.
This fixed the problem:
string s = dl[rndIndex];
s = s.Replace(((char)13).ToString(), "");
Which is what you suggested.
The way the it replaces the beginning of the URL, it seems that dl[rndIndex] contains a carriage return which places the cursor back to the beginning of the line and then overwrites the https:/ part of the URL (which fits as /3?dl=1 has the same length).
So your formatted string actually looks like this:
"https://www.dropbox.com/s/s8ghw2mvld2jg0l\r/3?dl=1"
^^
carriage return
Now when that is printed to a console which supports carriage returns, it will print the first part https://www.dropbox.com/s/s8ghw2mvld2jg0l then set the cursor back to the beginning and print the rest /3?dl=1.
So you should basically strip out all carriage returns from the string first. In any way it seems as if your dl array does not contain what you expect it to do.
I can reproduce the exact problem by #poke's comment:
string.Format("https://www.dropbox.com/s/{0}/{1}?dl=1", "hfjdhfjdh\r", 30)
will output:
/30?dl=1www.dropbox.com/s/hfjdhfjdh
The problem is a carriage return or new line character in your array elements.
Modifying your fragment as follows:
string[] dl = new string[] { "...", "...", "..." };
int rndIndex = 1; // rnd.Next(0, dl.Length);
Console.WriteLine(string.Format(#"https://www.dropbox.com/s/{0}/{1}?dl=1", dl[rndIndex], rndIndex));
Gives a correct answer.
https://www.dropbox.com/s/.../1?dl=1
So, two thoughts:
It's a data dependent problem
Should the random function not read rnd.Next(0, dl.Length-1)
I have this kind of text:
LINE\r\n 5\r\n11DA3\r\n330\r\n2\r\n100\r\nAcDbEntity\r\n
8\r\n0-FD\r\n 6\r\nHIDDEN\r\n100
Take a look at the text in bold. I would like to replace the text between 5\r\n and \r\n100. I tried this code:
result[line] = Regex.Replace(result[line], #"((?<=5\r\n)(\S+?)(?=\r\n100))", "0");
But it doesn't work. Is there something wrong with my code? I was sure the (\S+?) is the problem. Any way to solve it?
you can use the code:
string type_1 = "LINE\r\n 5\r\n11DA3\r\n330\r\n2\r\n100\r\nAcDbEntity\r\n 8\r\n0-FD\r\n 6\r\nHIDDEN\r\n100";
string output = Regex.Replace (
type_1,
"5\r\n(.*?)\r\n100",
"5\r\n0\r\n100",
RegexOptions.Singleline|RegexOptions.Compiled
);
Console.WriteLine (output);
it outputs:
LINE
5
0
100,1
AcDbEntity
8
0-FD
6
HIDDEN
100
It will change all encounters of text 5\r\n - ANYTHING HERE - \r\n100 to 5\r\n0\r\n100. If you want a more specific change please let me know.
If the removable Contents are Static you can use
s.Replace("11DA3\r\n330\r\n2" ,100);
Or even you can try with string.indexof