|
-
Oct 5th, 2015, 08:13 AM
#1
Thread Starter
Frenzied Member
[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;
}
}
Last edited by FishGuy; Oct 5th, 2015 at 12:25 PM.
-
Oct 6th, 2015, 01:56 AM
#2
Addicted Member
Re: Removing a section from a string
Try this:
- first split to array
- with LINQ remove elements in array which contains "sq.ft".
-
Oct 6th, 2015, 03:38 AM
#3
Re: Removing a section from a string
 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.
-
Oct 8th, 2015, 09:41 AM
#4
Thread Starter
Frenzied Member
Re: Removing a section from a string
Good solution, thank you. Much neater than my solution.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|