white space issue with UIText field - iphone

i have an UITextField which is allowing space
using the following code snippet it trims all the white space from the string (Text Field Text)
NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSString *trimmed = [rawString stringByTrimmingCharactersInSet:whitespace];
but i want to trim only the starting space of the Text that means
Example: #" SAMPLE TEXT"= #"SAMPLE TEXT"
can any one help me how to achieve this

First find the first character that is not a whitespace or newline. Then create a substring from that character's location and onwards.
NSString *justLeaveAPonyTail = #" Bla bla bla ";
NSCharacterSet *allExceptWhitespace = [[NSCharacterSet whitespaceAndNewlineCharacterSet] invertedSet];
NSRange range = [justLeaveAPonyTail rangeOfCharacterFromSet:allExceptWhitespace];
if (range.location != NSNotFound)
{
justLeaveAPonyTail = [justLeaveAPonyTail substringFromIndex:range.location];
}
// justLeaveAPonyTail is now #"Bla bla bla "

NSString *str = #" SAMPLE TEXT";
NSString *newStr = [str substringFromIndex:1];

Try this:
NSString *String = #" SAMPLE TEXT";
NSString *firstLetter = [String substringToIndex:0];
if ([firstLetter isEqualToString:#" "])
String = [String stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:#""];

Related

Substring after substring in NSString

I am new in objective and I'm facing my first problem, and I can not continue my first project.
it's quite simple, I have a NSString :
NSString *myString = #"<font face='Helvetica' size=25 color='#d79198'> Here is some text !</font>";
what I want to do is to get the value of the size "25" which is always 2 char long, so I can calculate my UILabel size.
i know how to detect if there is the substring I am looking for "size=" using :
if ([string rangeOfString:#"bla"].location == NSNotFound)
but I have not found or not understand how to extract the string #"size=XX" and then get the XX as a NSString from *myString
Thank for any help.
NSString *myString = #"<font face='Helvetica' size=25 color='#d79198'> Here is some text !</font>";
NSRange range = [myString rangeOfString:#"size="];
if (range.location != NSNotFound)
{
NSLog(#"Found \"size=\" at %d", range.location);
NSString *sizeString = [myString substringWithRange:NSMakeRange(range.location+5, 2)];
NSLog(#"sizeString: %#", sizeString);
}
This should do the trick. You could also at the end do this: int sizeFont = [sizeString intValue];
NSString *myString = #"<font face='Helvetica' size=25 color='#d79198'> Here is some text !</font>";
if ([myString rangeOfString:#"size"].location != NSNotFound)
{
myString = [myString substringFromIndex:[myString rangeOfString:#"size"].location];
myString = [myString substringToIndex:[myString rangeOfString:#" "].location]; // Now , myString ---> size=25 color='#d79198'> Here is some text !</font>
myString = [myString substringFromIndex:[myString length]-2];// Now, myString ---> size=25
NSLog(#"myString -- %#",myString); // Now, myString ---> 25
}
If you have string like stack:overflow then use it as follow :
NSString *Base=#"stack:overflow"
NSString *one = [[Base componentsSeparatedByString:#":"] objectAtIndex:0];
NSString *two = [[Base componentsSeparatedByString:#":"] objectAtIndex:1];
In this case one = stack and two=overflow
Part of an HTML page? Then use the tool that is designed for the task.
You could calculate the range of the number yourself or use a very simple regular expression to get the substring, something like
(?<=size\=)\d*
This means that you are searching for digits (\d*) that is preceded by "size=" ((?<=size\=))
Which using NSRegularExpression would be
NSError *error = NULL;
NSRegularExpression *regex =
[NSRegularExpression regularExpressionWithPattern:#"(?<=size\\=)\\d*"
options:0
error:&error];
NSTextCheckingResult *match =
[regex firstMatchInString:myString
options:0
range:NSMakeRange(0, [myString length])];
NSString *sizeText = [myString substringWithRange:match.range];
Finally you should convert the text "25" into a number using
NSInteger size = [sizeText integerValue];
Use componentsSeparatedByString: method...
NSString *myString = #"<font face='Helvetica' size=25 color='#d79198'> Here is some text !</font>";
NSString *theSizeString = [[[[myString componentsSeparatedByString:#" "] objectAtIndex:2] componentsSeparatedByString:#"="] objectAtIndex:1];
NSLog(#"The sizestring:%#",theSizeString);
I think it will be helpful to you.
You can get the range of the string #"size=". The range has location and length. So what you need next is to call on the myString the substringWithRange: method. The parameter would be an NSRage starting from the location+length of #"size=" and length of 2.

Find the index of a character in a string

I have a string NSString *Original=#"88) 12-sep-2012"; or Original=#"8) blablabla";
I want to print only the characters before the ")" so how to find the index of the character ")". or how could i do it?
Thanks in advance.
To print the characters before the first right paren, you can do this:
NSString *str = [[yourString componentsSeparatedByString:#")"] objectAtIndex:0];
NSLog(#"%#", str);
// If you need the character index:
NSUInteger index = str.length;
U can find index of the character ")" like this:
NSString *Original=#"88) 12-sep-2012";
NSRange range = [Original rangeOfString:#")"];
if(range.location != NSNotFound)
{
NSString *result = [Original substringWithRange:NSMakeRange(0, range.location)];
}
You can use the following code to see the characters before ")"
// this would split the string into values which would be stored in an array
NSArray *splitStringArray = [yourString componentsSeparatedByString:#")"];
// this would display the characters before the character ")"
NSLog(#"%#", [splitStringArray objectAtIndex:0]);
NSUInteger index = [Original rangeOfString:#")"];
NSString *result = [Original substringWithRange:NSMakeRange(0, index)];
try the below code to get the index of a particular character in a string:-
NSString *string = #"88) 12-sep-2012";
NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:#")"];
NSRange range = [string rangeOfCharacterFromSet:charSet];
if (range.location == NSNotFound)
{
// ... oops
}
else {
NSLog(#"---%d", range.location);
// range.location is the index of character )
}
and to get the string before the ) character use this:-
NSString *str = [[string componentsSeparatedByString:#")"] objectAtIndex:0];
Another soluation:
NSString *Original=#"88) 12-sep-2012";
NSRange range = [Original rangeOfString:#")"];
NSString *result = Original;
if (range.location != NSNotFound)
{
result = [Original substringToIndex:range.location];
}
NSLog(#"Result: %#", result);

How to detect UISearchBar is containing blank spaces only

How to detect if UISearchBar contains only blank spaces not any other character or string and replace it with #""?
You can trim the string with a character set containing whitespace using the NSString stringByTrimmingCharactersInSet message (using the whitespaceCharacterSet):
NSString * searchString = [searchBar.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
if (![searchString length])
// return ... search bar was just whitespace
You can check as
[yourSearchBar.text isEqualToString:#""]
Hope it helps.
if([searchBar.text isEqualToString:#""] && [searchBar.text length] ==0){
// Blank Space in searchbar
else{
// Do Search
}
Use isEqualToString method of NSString
Use stringByTrimmingCharactersInSet to trim the character from NSString.
- (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set
Use as below.
NSString* myString = mySearchBar.text
myString = [myString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
Here's how you detect and replace it: (assuming the UISearchField is called searchBar)
NSString*replacement;
if ([searchBar.text isEqualToString:#" "])
{
replacement = [NSString stringByReplacingOccurancesOfString:#" " withString:#""];
}
searchBar.text = replacement;
Have a look in the Apple Documentation for NSString for more.
Edit:
If you have more than once space, do this:
NSString *s = [someString stringByReplacingOccurrencesOfString:#" "
withString:#""
options:NSRegularExpressionSearch
range:NSMakeRange(0, [someString length])
];
searchBar.text = s;
This worked for me: if you are using #"" or length already to control say a button then this version really does detect the whitespace, if a space has been entered...
if([activeField.text isEqualToString:#" "] && [activeField.text length] ==1){
// Blank Space in searchbar
{
// an alert example
}

How to remove whitespace in a string?

I have a string say "Allentown, pa"
How to remove the white space in between , and pa using objective c?
This will remove all space from myString.
NSString *newString = [myString stringByReplacingOccurrencesOfString:#" " withString:#""];
Here is a proper and documented way of removing white spaces from your string.
whitespaceCharacterSet Apple Documentation for iOS says:
Returns a character set containing only the in-line whitespace characters space (U+0020) and tab (U+0009).
+ (id)whitespaceCharacterSet
Return Value
A character set containing only the in-line whitespace characters space (U+0020) and tab (U+0009).
Discussion
This set doesn’t contain the newline or carriage return characters.
Availability
Available in iOS 2.0 and later.
You can use this documented way:
[yourString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
Hope this helps you.
If you need any more help then please let me know on this.
Probably the solution in one of the answers in Collapse sequences of white space into a single character and trim string:
NSString *whitespaceString = #" String with whitespaces ";
NSString *trimmedString = [whitespaceString stringByReplacingOccurrencesOfString:#" " withString:#""];
If you want to white-space and new-line character as well then use "whitespaceAndNewlineCharacterSet" instead of "whitespaceCharacterSet"
NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
NSString *trimmedString = [temp.text stringByTrimmingCharactersInSet:whitespace];
NSLog(#"Value of the text field is %#",trimmedString);
myStr = [myStr stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *sample = #" string with whitespaces";
NSString *escapeWhiteSpaces = [sample stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
- (NSString *)removeWhitespaces {
return [[self componentsSeparatedByCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]]
componentsJoinedByString:#""];
}
In my case NSString was added Zero Width Space(i i used some library). so solution worked for me.
NSMutableString *newString=[[newString stringByReplacingOccurrencesOfString:#"\u200B" withString:#""] mutableCopy];
#"\u200B" is Zero width space character value.
Here is the proper way to remove extra whitespaces from string which is coming in between.
NSString *yourString = #"Allentown, pa";
NSCharacterSet *whitespaces = [NSCharacterSet whitespaceCharacterSet];
NSPredicate *noEmptyStrings = [NSPredicate predicateWithFormat:#"SELF != ''"];
NSArray *parts = [yourString componentsSeparatedByCharactersInSet:whitespaces];
NSArray *filteredArray = [parts filteredArrayUsingPredicate:noEmptyStrings];
yourString = [filteredArray componentsJoinedByString:#" "];
you can use remove function to remove any substring from the string
- (NSString*)remove:(NSString*)textToRemove fromString:(NSString*)input {
return [input stringByReplacingOccurrencesOfString:textToRemove withString:#""];
}
I have tried all the solutions here, none of them could remove the whitespace generated by the Chinese PinYin Input method.
After some debugging, I found this working:
NSString *newString = [myString stringByReplacingOccurrencesOfString:#"\342\200\206" withString:#""];
I have googled what the '\342\200\206' is, but failed.
Whatever, it works for me.
Hi there is the swift version of the solution with extension :
extension String{
func deleteSpaces() -> String{
return self.stringByReplacingOccurrencesOfString(" ", withString: "")
}
}
And Just call
(yourString as! String).deleteSpaces()
Swift 3:
var word: String = "Hello world"
let removeWhiteSpace = word.stringByRemovingWhitespaces
word = "Helloworld"

How do you remove extra empty space in NSString?

is there a simple way to remove the extra spaces in a string? ie like...
NSString *str = #"this string has extra empty spaces";
result should be:
NSString *str = #"this string has extra empty spaces";
Thanks!
replace all double space with a single space until there are no more double spaces in your string.
- (NSString *)stripDoubleSpaceFrom:(NSString *)str {
while ([str rangeOfString:#" "].location != NSNotFound) {
str = [str stringByReplacingOccurrencesOfString:#" " withString:#" "];
}
return str;
}