[RESOLVED] Removing a section from a string
I have a string which contains comma delimited text and I need to remove a section if it contains the specific substring "sq.ft".
For example "colour red, size tall, carpeted throughout lower floor, 2000 sq.ft, tiled roof"
So I need to remove " 2000 sq.ft,"
I can find the middle of the section of string I need to remove using indexof("sq.ft") and the end but what is the best way to find the start? i.e. the position after the comma at the start of the string section (the last preceding comma before the "sq.ft") I could loop through each character upto the known position and check if it is a char ',' but im sure there must be a better faster way?
Code:
protected void GetUnitWithoutSqFt()
{
UnitWithoutSqFt = Unit.Model;
if (Unit.Model.ToLower().IndexOf("sq.ft") > -1) ;
{
int x = Unit.Model.ToLower().IndexOf("sq.ft");
int z = 0;
int n = Unit.Model.ToLower().IndexOf(',');
if (n > -1)
{
for (int i = Unit.Model.ToLower().IndexOf(',');
i > -1;
i = Unit.Model.ToLower().IndexOf(',', i + 1))
{
// for loop end when i=-1 ('a' not found)
z = i;
}
}
int y = 0;
y = Unit.Model.ToLower().IndexOf(",", x);
if (y == -1)
{
y = x + 5;
}
int len = y - z;
if (z > -1 && len > 0)
UnitWithoutSqFt = Unit.Model.Remove(z, len);
// UnitWithoutSqFt = "z" + z + "y" + y +"n" +n;
}
}
Re: Removing a section from a string
Try this:
- first split to array
- with LINQ remove elements in array which contains "sq.ft".
Re: Removing a section from a string
Quote:
Originally Posted by
Blagojce
Try this:
- first split to array
- with LINQ remove elements in array which contains "sq.ft".
Then use String.Join to rejoin the remaining substrings. It can all be done in one line if you like.
Re: Removing a section from a string
Good solution, thank you. Much neater than my solution.