Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Detect if label contains double space

How would I replace double spaces in a label with a single space?

1 Answer

try something like.

if (label.text == "  ") {

   label.text = " ";

}

the label references may be incorrect, it could be something like self.label.text = whatever but I havent really done much iOS development lately so I cant remember exactly

Does this check if the label contains it or is equal to that? The label may have other words in it.

e.g. @"Treehouse is great!"

ah this is checking if the label only contains the double space. to check if the label has a double space

using the code posted here

NSString *myString = label.text;
NSRange rangeValue = [myString rangeOfString:@" " options:NSCaseInsensitiveSearch];

if (rangeValue.length > 0){

NSLog(@"string contains two spaces");

} 

else {

NSLog(@"string does not contain two spaces");

}

As far as replacing it with a space might be a bit more difficult.

you could use the location property of the range

rangeValue.location 

to give you the index of the array where the double space starts.

you could then create a substring for the first part of the string up to the double space

NSString *firstHalf = [self.text substringWithRange:NSMakeRange(0, rangeValue.location)];

and then use the same method again to give the last half just after the double space and concatenate the 2 strings together