Trim string from END - iphone

I want to string string from the end of string, is there any api function of string which ONLY removes Space and Newline from END of string.
I wrote manual code to search character from end of string and remove space and newline but it may slow the process.
API function needed..
Thanks in advance

try this one may be it helps you,
-(NSString *)removeEndSpaceFrom:(NSString *)strtoremove{
NSUInteger location = 0;
unichar charBuffer[[strtoremove length]];
[strtoremove getCharacters:charBuffer];
int i = 0;
for ( i = [strtoremove length]; i >0; i--){
if (![[NSCharacterSet whitespaceCharacterSet] characterIsMember:charBuffer[i - 1]]){
break;
}
}
return [strtoremove substringWithRange:NSMakeRange(location, i - location)];
}
and
NSString *string = #" this text has spaces before and after ";
NSString *trimmedString = [self removeEndSpaceFrom:string];
NSLog(#"%#",trimmedString);

Related

Replace unicode value in string

I have a string #"\EOP". I want to dislpay this to user. But when i display this string in textfield, It shows only OP. I tried to print that in console while debugging and it shows ¿OP
So \E is unicode value and that's why it's having some issue of encoding. I can fix this issue by:
NSString *str=[str stringByReplacingOccurrencesOfString:#"\E" withString:#"\\E"];
With this it will display perfect string #"\EOP".
Here my issue is that there can be many more characters same like \E for example \u. How can I implement one fix for all these kind of characters?
\E in the string #"\EOP" is the character with the ASCII-code (or Unicode) 27,
which is a control character.
I don't know of a built-in method to escape all control characters in a string.
The following code uses NSScanner to locate the control characters, and replaces them
using a lookup-table. The control characters are replaced by "Character Escape Codes"
such as "\r" or "\n" if possible, otherwise by "\x" followed by the hex-code.
NSString *str = #"\EOP";
NSCharacterSet *controls = [NSCharacterSet controlCharacterSet];
static char *replacements[] = {
"0", NULL, NULL, NULL, NULL, NULL, NULL, "\\a",
"\\b", "\\t", "\\n", "\\v", "\\f", "\\r", NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, "\\e"};
NSScanner *scanner = [NSScanner scannerWithString:str];
[scanner setCharactersToBeSkipped:nil];
NSMutableString *result = [NSMutableString string];
while (![scanner isAtEnd]) {
NSString *tmp;
// Copy all non-control characters verbatim:
if ([scanner scanUpToCharactersFromSet:controls intoString:&tmp]) {
[result appendString:tmp];
}
if ([scanner isAtEnd])
break;
// Escape all control characters:
if ([scanner scanCharactersFromSet:controls intoString:&tmp]) {
for (int i = 0; i < [tmp length]; i++) {
unichar c = [tmp characterAtIndex:i];
char *r;
if (c < sizeof(replacements)/sizeof(replacements[0])
&& (r = replacements[c]) != NULL) {
// Replace by well-known character escape code:
[result appendString:#(r)];
} else {
// Replace by \x<hexcode>:
[result appendFormat:#"\\x%02x", c];
}
}
}
}
NSLog(#"%#", result);
You can always replace \ with \\. These are called Escape Sequences.
Sample Code :
NSString *str = #"\EOP";
NSString *myNewStr = [str stringByReplacingOccurrencesOfString:#"\\" withString:#"\\\\"];
NSLog(#"myNewStr :: %#",myNewStr);
If you want a backslash (\) to appear in a string literal, you need to escape it in the string literal i.e.
NSString* foo = #"\\EOP";
The above will give you the Unicode sequence 5C 45 4F 50 which is what you want.

Extract part of NSString

My app gets the string from an RSS feed for the preview image. It displays in this format:
<p><img class="alignnone size-full wp-image-22" title="144x144" src="http://316apps.com/LakesideNews/wp-content/uploads/2012/05/144x1443.png" alt="" width="144" height="144" /></p>
hi
I am parsing the rss using GDATAXML and tutorial from Ray Wenderlich's blog. I set up an NSString to the value that is given in the RSS for the image. I then set up an NSLog with that string. What the NSLog returns is what I had put in the original post. Is there a way to subString it to get just the part between " "?
use NSRange, but you'll need to determine the start point and length (the position of the two quotes)
[untested code]
int idStart = 0;
int idEnd = 0;
for (int f = 0; f < [initialString length]; f++) {
NSRange myRangeStart;
myRangeStart.location = f;
myRangeStart.length = 1;
substr = [urlStr substringWithRange:myRangeStart];
if ( idStart == 0) {
if ([substr isEqualToString:#"\""]) {
idStart = f;
}
} else {
if ([substr isEqualToString:#"\""] && f > idStart) {
idEnd = f;
}
}
}
NSString* substring = #"";
NSRange myRange;
myRange.location = idStart+1;
myRange.length = idEnd-idStart-1;
substring = [initialString substringWithRange:myRange];
[/untested code]
Take a look at NSXMLParser in Apple's documentation. You should be able to use the string as NSData and parse it with that object.

Apply regular expression repeatedly

I've got text expressions like this:
HIUPA:bla1bla1'HIUPD:bla2bla2'HIUPD:bla3bla3'HISYN:bla4bla4'
I want to extract the following text pieces:
HIUPD:bla2bla2'
And
HIUPD:bla3bla3'
My Objective-C code for this looks like this:
-(void) ermittleKonten:(NSString*) bankNachricht
{
NSRegularExpression* regexp;
NSTextCheckingResult* tcr;
regexp = [NSRegularExpression regularExpressionWithPattern:#"HIUPD.*'" options:0 error:nil];
int numAccounts = [regexp numberOfMatchesInString:bankNachricht options:0 range:NSMakeRange(0, [bankNachricht length])];
for( int i = 0; i < numAccounts; ++i ) {
tcr = [regexp firstMatchInString:bankNachricht options:0 range:NSMakeRange( 0, [bankNachricht length] )];
NSString* HIUPD = [bankNachricht substringWithRange:tcr.range];
NSLog(#"Found text is:\n%#", HIUPD);
}
}
In the Objective-C code numAccounts is 1, but should be 2. And the string that is found is "HIUPD:bla2bla2'HIUPD:bla3bla3'HISYN:bla4bla4'"
I tested the regular expression pattern with an online tool ( http://www.regexplanet.com/simple/index.html ). In the online tool it works fine and delivers 2 results as I want it to be.
But I would like to have the same result in the ios code, i.e. "HIUPD:bla2bla2'" and "HIUPD:bla3bla3'". What is wrong with the pattern?
You're doing greedy matching with the .*, so the regular expression catches as much as it can in the .*. You should be doing .*?, or [^']*, so that the * can't match a '.

How to check if NSString is contains a numeric value?

I have a string that is being generate from a formula, however I only want to use the string as long as all of its characters are numeric, if not that I want to do something different for instance display an error message.
I have been having a look round but am finding it hard to find anything that works along the lines of what I am wanting to do. I have looked at NSScanner but I am not sure if its checking the whole string and then I am not actually sure how to check if these characters are numeric
- (void)isNumeric:(NSString *)code{
NSScanner *ns = [NSScanner scannerWithString:code];
if ( [ns scanFloat:NULL] ) //what can I use instead of NULL?
{
NSLog(#"INSIDE IF");
}
else {
NSLog(#"OUTSIDE IF");
}
}
So after a few more hours searching I have stumbled across an implementation that dose exactly what I am looking for.
so if you are looking to check if their are any alphanumeric characters in your NSString this works here
-(bool) isNumeric:(NSString*) hexText
{
NSNumberFormatter* numberFormatter = [[[NSNumberFormatter alloc] init] autorelease];
NSNumber* number = [numberFormatter numberFromString:hexText];
if (number != nil) {
NSLog(#"%# is numeric", hexText);
//do some stuff here
return true;
}
NSLog(#"%# is not numeric", hexText);
//or do some more stuff here
return false;
}
hope this helps.
Something like this would work:
#interface NSString (usefull_stuff)
- (BOOL) isAllDigits;
#end
#implementation NSString (usefull_stuff)
- (BOOL) isAllDigits
{
NSCharacterSet* nonNumbers = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
NSRange r = [self rangeOfCharacterFromSet: nonNumbers];
return r.location == NSNotFound && self.length > 0;
}
#end
then just use it like this:
NSString* hasOtherStuff = #"234 other stuff";
NSString* digitsOnly = #"123345999996665003030303030";
BOOL b1 = [hasOtherStuff isAllDigits];
BOOL b2 = [digitsOnly isAllDigits];
You don't have to wrap the functionality in a private category extension like this, but it sure makes it easy to reuse..
I like this solution better than the others since it wont ever overflow some int/float that is being scanned via NSScanner - the number of digits can be pretty much any length.
Consider NSString integerValue - it returns an NSInteger. However, it will accept some strings that are not entirely numeric and does not provide a mechanism to determine strings which are not numeric at all. This may or may not be acceptable.
For instance, " 13 " -> 13, "42foo" -> 42 and "helloworld" -> 0.
Happy coding.
Now, since the above was sort of a tangent to the question, see determine if string is numeric. Code taken from link, with comments added:
BOOL isNumeric(NSString *s)
{
NSScanner *sc = [NSScanner scannerWithString: s];
// We can pass NULL because we don't actually need the value to test
// for if the string is numeric. This is allowable.
if ( [sc scanFloat:NULL] )
{
// Ensure nothing left in scanner so that "42foo" is not accepted.
// ("42" would be consumed by scanFloat above leaving "foo".)
return [sc isAtEnd];
}
// Couldn't even scan a float :(
return NO;
}
The above works with just scanFloat -- e.g. no scanInt -- because the range of a float is much larger than that of an integer (even a 64-bit integer).
This function checks for "totally numeric" and will accept "42" and "0.13E2" but reject " 13 ", "42foo" and "helloworld".
It's very simple.
+ (BOOL)isStringNumeric:(NSString *)text
{
NSCharacterSet *alphaNums = [NSCharacterSet decimalDigitCharacterSet];
NSCharacterSet *inStringSet = [NSCharacterSet characterSetWithCharactersInString:text];
return [alphaNums isSupersetOfSet:inStringSet];
}
Like this:
- (void)isNumeric:(NSString *)code{
NSScanner *ns = [NSScanner scannerWithString:code];
float the_value;
if ( [ns scanFloat:&the_value] )
{
NSLog(#"INSIDE IF");
// do something with `the_value` if you like
}
else {
NSLog(#"OUTSIDE IF");
}
}
Faced same problem in Swift.
In Swift you should use this code, according TomSwift's answer:
func isAllDigits(str: String) -> Bool {
let nonNumbers = NSCharacterSet.decimalDigitCharacterSet()
if let range = str.rangeOfCharacterFromSet(nonNumbers) {
return true
}
else {
return false
}
}
P.S. Also you can use other NSCharacterSets or their combinations to check your string!
For simple numbers like "12234" or "231231.23123" the answer can be simple.
There is a transformation law for int numbers: when string with integer transforms to int (or long) number and then, again, transforms it back to another string these strings will be equal.
In Objective C it will looks like:
NSString *numStr=#"1234",*num2Str=nil;
num2Str=[NSString stringWithFormat:#"%lld",numStr.longlongValue];
if([numStr isEqualToString: num2Str]) NSLog(#"numStr is an integer number!");
By using this transformation law we can create solution
to detect double or long numbers:
NSString *numStr=#"12134.343"
NSArray *numList=[numStr componentsSeparatedByString:#"."];
if([[NSString stringWithFormat:#"%lld", numStr.longLongValue] isEqualToString:numStr]) NSLog(#"numStr is an integer number");
else
if( numList.count==2 &&
[[NSString stringWithFormat:#"%lld",((NSString*)numList[0]).longLongValue] isEqualToString:(NSString*)numList[0]] &&
[[NSString stringWithFormat:#"%lld",((NSString*)numList[1]).longLongValue] isEqualToString:(NSString*)numList[1]] )
NSLog(#"numStr is a double number");
else
NSLog(#"numStr is not a number");
I did not copy the code above from my work code so can be some mistakes, but I think the main point is clear.
Of course this solution doesn't work with numbers like "1E100", as well it doesn't take in account size of integer and fractional part. By using the law described above you can do whatever number detection you need.
C.Johns' answer is wrong. If you use a formatter, you risk apple changing their codebase at some point and having the formatter spit out a partial result. Tom's answer is wrong too. If you use the rangeOfCharacterFromSet method and check for NSNotFound, it'll register a true if the string contains even one number. Similarly, other answers in this thread suggest using the Integer value method. That is also wrong because it will register a true if even one integer is present in the string. The OP asked for an answer that ensures the entire string is numerical. Try this:
NSCharacterSet *searchSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
Tom was right about this part. That step gives you the non-numerical string characters. But then we do this:
NSString *trimmedString = [string stringByTrimmingCharactersInSet:searchSet];
return (string.length == trimmedString.length);
Tom's inverted character set can TRIM a string. So we can use that trim method to test if any non numerals exist in the string by comparing their lengths.

Objective-c iPhone percent encode a string?

I would like to get the percent encoded string for these specific letters, how to do that in objective-c?
Reserved characters after percent-encoding
! * ' ( ) ; : # & = + $ , / ? # [ ]
%21 %2A %27 %28 %29 %3B %3A %40 %26 %3D %2B %24 %2C %2F %3F %23 %5B %5D
Percent-encoding wiki
Please test with this string and see if it do work:
myURL = #"someurl/somecontent"
I would like the string to look like:
myEncodedURL = #"someurl%2Fsomecontent"
I tried with the stringByAddingPercentEscapesUsingEncoding: NSASCIIStringEncoding already but it does not work, the result is still the same as the original string. Please advice.
I've found that both stringByAddingPercentEscapesUsingEncoding: and CFURLCreateStringByAddingPercentEscapes() are inadequate. The NSString method misses quite a few characters, and the CF function only lets you say which (specific) characters you want to escape. The proper specification is to escape all characters except a small set.
To fix this, I created an NSString category method to properly encode a string. It will percent encoding everything EXCEPT [a-zA-Z0-9.-_~] and will also encode spaces as + (according to this specification). It will also properly handle encoding unicode characters.
- (NSString *) URLEncodedString_ch {
NSMutableString * output = [NSMutableString string];
const unsigned char * source = (const unsigned char *)[self UTF8String];
int sourceLen = strlen((const char *)source);
for (int i = 0; i < sourceLen; ++i) {
const unsigned char thisChar = source[i];
if (thisChar == ' '){
[output appendString:#"+"];
} else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' ||
(thisChar >= 'a' && thisChar <= 'z') ||
(thisChar >= 'A' && thisChar <= 'Z') ||
(thisChar >= '0' && thisChar <= '9')) {
[output appendFormat:#"%c", thisChar];
} else {
[output appendFormat:#"%%%02X", thisChar];
}
}
return output;
}
The iOS 7 SDK now has a better alternative tostringByAddingPercentEscapesUsingEncoding that does let you specify that you want all characters escaped except certain allowed ones. It works well if you are building up the URL in parts:
NSString * unescapedQuery = [[NSString alloc] initWithFormat:#"?myparam=%d", numericParamValue];
NSString * escapedQuery = [unescapedQuery stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSString * urlString = [[NSString alloc] initWithFormat:#"http://ExampleOnly.com/path.ext%#", escapedQuery];
Although it's less often that the other parts of the URL will be variables, there are constants in the NSURLUtilities category for those as well:
[NSCharacterSet URLHostAllowedCharacterSet]
[NSCharacterSet URLUserAllowedCharacterSet]
[NSCharacterSet URLPasswordAllowedCharacterSet]
[NSCharacterSet URLPathAllowedCharacterSet]
[NSCharacterSet URLFragmentAllowedCharacterSet]
[NSCharacterSet URLQueryAllowedCharacterSet] includes all of the characters allowed in the query part of the URL (the part starting with the ? and before the # for a fragment, if any) including the ? and the & or = characters, which are used to delimit the parameter names and values. For query parameters with alphanumeric values, any of those characters might be included in the values of the variables used to build the query string. In that case, each part of the query string needs to be escaped, which takes just a bit more work:
NSMutableCharacterSet * URLQueryPartAllowedCharacterSet; // possibly defined in class extension ...
// ... and built in init or on first use
URLQueryPartAllowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy];
[URLQueryPartAllowedCharacterSet removeCharactersInString:#"&+=?"]; // %26, %3D, %3F
// then escape variables in the URL, such as values in the query and any fragment:
NSString * escapedValue = [anUnescapedValue stringByAddingPercentEncodingWithAllowedCharacters:URLQueryPartAllowedCharacterSet];
NSString * escapedFrag = [anUnescapedFrag stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
NSString * urlString = [[NSString alloc] initWithFormat:#"http://ExampleOnly.com/path.ext?myparam=%##%#", escapedValue, escapedFrag];
NSURL * url = [[NSURL alloc] initWithString:urlString];
The unescapedValue could even be an entire URL, such as for a callback or redirect:
NSString * escapedCallbackParamValue = [anAlreadyEscapedCallbackURL stringByAddingPercentEncodingWithAllowedCharacters:URLQueryPartAllowedCharacterSet];
NSURL * callbackURL = [[NSURL alloc] initWithString:[[NSString alloc] initWithFormat:#"http://ExampleOnly.com/path.ext?callback=%#", escapedCallbackParamValue]];
Note: Don't use NSURL initWithScheme:(NSString *)scheme host:(NSString *)host path:(NSString *)path for a URL with a query string because it will add more percent escapes to the path.
NSString *encodedString = [myString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
It won't replace your string inline; it'll return a new string. That's implied by the fact that the method starts with the word "string". It's a convenience method to instantiate a new instance of NSString based on the current NSString.
Note--that new string will be autorelease'd, so don't call release on it when you're done with it.
NSString's stringByAddingPercentEscapesUsingEncoding: looks like what you're after.
EDIT: Here's an example using CFURLCreateStringByAddingPercentEscapes instead. originalString can be either an NSString or a CFStringRef.
CFStringRef newString = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, originalString, NULL, CFSTR("!*'();:#&=+#,/?#[]"), kCFStringEncodingUTF8);
Please note that this is untested. You should have a look at the documentation page to make sure you understand the memory allocation semantics for CFStringRef, the idea of toll-free bridging, and so on.
Also, I don't know (off the top of my head) which of the characters specified in the legalURLCharactersToBeEscaped argument would have been escaped anyway (due to being illegal in URLs). You may want to check this, although it's perhaps better just to be on the safe side and directly specify the characters you want escaped.
I'm making this answer a community wiki so that people with more knowledge about CoreFoundation can make improvements.
Following the RFC3986 standard, here is what I'm using for encoding URL components:
// https://tools.ietf.org/html/rfc3986#section-2.2
let rfc3986Reserved = NSCharacterSet(charactersInString: "!*'();:#&=+$,/?#[]")
let encoded = "email+with+plus#example.com".stringByAddingPercentEncodingWithAllowedCharacters(rfc3986Reserved.invertedSet)
Output: email%2Bwith%2Bplus%40example.com
If you are using ASI HttpRequest library in your objective-c program, which I cannot recommend highly enough, then you can use the "encodeURL" helper API on its ASIFormDataRequest object. Unfortunately, the API is not static so maybe worth creating an extension using its implementation in your project.
The code, copied straight from the ASIFormDataRequest.m for encodeURL implementation, is:
- (NSString*)encodeURL:(NSString *)string
{
NSString *newString = NSMakeCollectable([(NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)string, NULL, CFSTR(":/?#[]#!$ &'()*+,;=\"<>%{}|\\^~`"), CFStringConvertNSStringEncodingToEncoding([self stringEncoding])) autorelease]);
if (newString) {
return newString;
}
return #"";
}
As you can see, it is essentially a wrapper around CFURLCreateStringByAddingPercentEscapes that takes care of all the characters that should be properly escaped.
Before I noticed Rob's answer, which appears to work well and is preferred as it's cleaner, I went ahead and ported Dave's answer to Swift. I'll leave it here in case anyone is interested:
public extension String {
// For performance, I've replaced the char constants with integers, as char constants don't work in Swift.
var URLEncodedValue: String {
let output = NSMutableString()
guard let source = self.cStringUsingEncoding(NSUTF8StringEncoding) else {
return self
}
let sourceLen = source.count
var i = 0
while i < sourceLen - 1 {
let thisChar = source[i]
if thisChar == 32 {
output.appendString("+")
} else if thisChar == 46 || thisChar == 45 || thisChar == 95 || thisChar == 126 ||
(thisChar >= 97 && thisChar <= 122) ||
(thisChar >= 65 && thisChar <= 90) ||
(thisChar >= 48 && thisChar <= 57) {
output.appendFormat("%c", thisChar)
} else {
output.appendFormat("%%%02X", thisChar)
}
i++
}
return output as String
}
}
In Swift4:
var str = "someurl/somecontent"
let percentEncodedString = str.addingPercentEncoding(withAllowedCharacters: .alphanumerics)