Objective-C - Remove last character from string - ios

In Objective-C for iOS, how would I remove the last character of a string using a button action?

In your controller class, create an action method you will hook the button up to in Interface Builder. Inside that method you can trim your string like this:
if ([string length] > 0) {
string = [string substringToIndex:[string length] - 1];
} else {
//no characters to delete... attempting to do so will result in a crash
}
If you want a fancy way of doing this in just one line of code you could write it as:
string = [string substringToIndex:string.length-(string.length>0)];
*Explanation of fancy one-line code snippet:
If there is a character to delete (i.e. the length of the string is greater than 0)
     (string.length>0) returns 1 thus making the code return:
          string = [string substringToIndex:string.length-1];
If there is NOT a character to delete (i.e. the length of the string is NOT greater than 0)
     (string.length>0) returns 0 thus making the code return:
          string = [string substringToIndex:string.length-0];
     Which prevents crashes.

If it's an NSMutableString (which I would recommend since you're changing it dynamically), you can use:
[myString deleteCharactersInRange:NSMakeRange([myRequestString length]-1, 1)];

The solutions given here actually do not take into account multi-byte Unicode characters ("composed characters"), and could result in invalid Unicode strings.
In fact, the iOS header file which contains the declaration of substringToIndex contains the following comment:
Hint: Use with rangeOfComposedCharacterSequencesForRange: to avoid breaking up composed characters
See how to use rangeOfComposedCharacterSequenceAtIndex: to delete the last character correctly.

The documentation is your friend, NSString supports a call substringWithRange that can shorten the string that you have an return the shortened String. You cannot modify an instance of NSString it is immutable. If you have an NSMutableString is has a method called deleteCharactersInRange that can modify the string in place
...
NSRange r;
r.location = 0;
r.size = [mutable length]-1;
NSString* shorted = [stringValue substringWithRange:r];
...

Related

NSMutable String: How do I get the index of multiple spaces in a string?

I want to find the index of the 8th occurrence of " " so that I could split my string there. However all I can find is this line of code that gives me an array of all the occurrences of " ". Is there a function I can call that would give me this information?
int numberOfOccurences = [[myListString componentsSeparatedByString:#" "] count];
Edit 1: So far this is the solution I came up with:
if(numberOfOccurences > 8)
{
//find index of place where you want to split by picking an
//arbitrary number and finding the first white space
int index = (int)[[myListString substringFromIndex:45] rangeOfString:#" "].location;
NSLog(#"Index: %i", index);
//make substring
NSString *substringList1 = [myListString substringToIndex:(45+index)];
NSString *substringList2 = [myListString substringFromIndex:(45+index)];
}
There is no method to find the 8th space, but there are the building blocks you need.
The NSString method rangeOfString:options:range: will find the first occurrence of its first argument within the range specified by its third argument, it returns a range for the match. You simply start with the third argument being the whole string and then iterate reducing the range to search using the previous result.
If you are actually looking for white space and not simply a space you might consider the similar rangeOfCharactersFromSet methods.
If you don't really want the eighth space, but are trying to break a string at a given length, you can look at componentsSeparatedByString/componentsSeparatedByCharactersInSet and then reassemble the resultant “words" into strings of the appropriate length. You might also want to look at NSScanner.
HTH
With the explicit assumption that you are looking for the eighth space (and possibly needing to adjust the regex a little depending on character set), you could use a regular expression:
NSRegularExpression *exp = [NSRegularExpression regularExpressionWithPattern:#"^([^ ]* ){8}+"
options:0
error:NULL];
NSRange result = [exp rangeOfFirstMatchInString:input options:0 range:inputRange];
If result.location != NSNotFound then result.length gives you the index on which to split.

Remove BackEnd character in a 'NSString'

I'm facing a problem when I try to remove a character in a 'NSString'. The character is a backend (\n).
My 'NSString' is for example like this :
My text is
also in a second line
And I want to get all in one line like this :
My text is also in a second line
The problem is I don't know how to change this...
I tried to locate the '\n' characters with a loop :
for (int delete = 0; delete < myString.length; delete++)
{
if ([myString characterAtIndex:delete] == 10)
{
[myString stringByReplacingCharactersInRange:NSMakeRange(delete,0) withString:#" "];
}
}
Or things like :
myString = [myString stringByReplacingOccurrencesOfString:#"\r" withString:#" "];
(I see that \r could be the backend in a nslog...)
Nothings work..
Thank you for your help in advance !
myString = [myString stringByReplacingOccurrencesOfString:#"\n" withString:#""];
is correct.
If it doesn't work, then the assumption that there is a combination of "\" and "n" characters is wrong.
Do not use NSLog. NSLog already applies carriage returns to the string. Instead put a breakpoint on the line where we call stringByReplacing... and then hover over the myString. Wait a second or two and you will see the "original unformatted content"...this way you can check what you are really trying to replace..

Printing the length of a string from a label

I am currently trying to check the length of a label.
What it is is i want the label to display "Unavailable" if the string is of a null value.
The sting is being read in from a XML sheet so i don't know what the length of the actual string is and i would like to know. This is what i currently have but its not working.
It displays the relevant text if its not empty which is brilliant.
But its not displaying the text when it is empty which is leading me to believe although i assume its empty its not.
Thanks in advance.
if ([l_subCommunity.text length] > 0)
{
[l_subCommunity setText:_property.str_subCommunity];
NSLog(#"%",l_subCommunity);
}
else
{
NSMutableString *sub = [[NSMutableString alloc]init];
[sub appendString:#"Unavailable"];
[self.l_subCommunity setText:sub];
}
[l_subCommunity setText:_property.str_subCommunity];
[self.l_subCommunity setText:sub];
you are using l_subCommunity setText in the if and self.l_subCommunity setText in the else. are you using 2 different variables?
Also why are you creating a mutable string to pass in the value #"Unavailable" ?
why not simply:
[self.l_subCommunity setText: #"Unavailable" ];
Your if statement is checking the wrong variable. You want:
if (_property.str_subCommunity.length) {
l_subCommunity.text = _property.str_subCommunity;
NSLog(#"%",l_subCommunity);
} else {
self.l_subCommunity.text = #"Unavailable";
}
Also keep in mind that you may end up with whitespace and/or newlines in your string as a result of parsing the XML file. You may need to trim this whitespace from your string.

objective c check string suffix from character set

I'm trying to check the suffix of a string against a character set but I'm getting errors:
if ([string hasSuffix:[NSCharacterSet characterSetWithCharactersInString:#"(+-*/"])
What am I doing wrong, is there a correct alternative?
-[NSString hasSuffix:] takes an NSString as its argument, not an NSCharacterSet. Your best bet is probably to call -[NSString rangeOfCharacterFromSet:options:] with NSBackwardsSearch as an option and check that the location is at the end of the string.
What are you trying to do?
I think that you are trying to see if the first letter of your string is one of the characters from the set. If so, then use this:
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:#"(+-*/"];
if ([[string substringToIndex:1] rangeOfCharacterFromSet:set].location != NSNotFound)
// String starts with one of the characters from the character set

NSString separation-iOS

I have following strings. But I need to separate them by this "jsonp1343930692" and assign them NSString again. How could I that? I could able to separate them to NSArray but I don't know how to separate to NSString.
jsonp1343930692("snapshot":[{"timestamp":1349143800,"data":[{"label_id":10,"lat":29.7161,"lng":-95.3906,"attr":{"ozone_level":37,"exp":"IN","gridpoint":"29.72:-95.39"}},{"label_id":10,"lat":30.168456,"lng":-95.50448}]}]})
jsonp1343930692("snapshot":[{"timestamp":1349144700,"data":[{"label_id":10,"lat":29.7161,"lng":-95.3906,"attr":{"ozone_level":37,"exp":"IN","gridpoint":"29.72:-95.39"}},{"label_id":10,"lat":30.168456,"lng":-95.50448,"attr":{"ozone_level":57,"exp":"IN","gridpoint":"30.17:-95.5"}},{"label_id":10,"lat":29.036944,"lng":-95.438333}]}]})
The jsonp1343930692 prefix in your string is odd: I don't know where you string come from, but it really seems to be some JSON string with this strange prefix that has no reason to be there. The best shot here is probably to check if it is normal to have this prefix, for example if you get this string from a WebService it is probably the WebService fault to return this odd prefix.
Anyway, if you want to remove the jsonp1343930692 prefix of your string, you have multiple options:
Check that the prefix is existant, and if so, remove the right number of characters from the original string:
NSString* str = ... // your string with the "jsonp1343930692" prefix
static NSString* kStringToRemove = #"jsonp1343930692";
if ([str hasPrefix:kStringToRemove])
{
// rebuilt a string by only using the substring after the prefix
str = [str substringFromIndex:kStringToRemove.length];
}
Split your string in multiple parts, using the jsonp1343930692 string as a separator
NSString* str = ... // your string with the "jsonp1343930692" prefix
static NSString* kStringToRemove = #"jsonp1343930692";
NSArray* parts = [str componentsSeparatedByString:kStringToRemove];
str = [parts componentsJoinedByString:#""];
Replace every occurrences of jsonp1343930692 by the empty string.
NSString* str = ... // your string with the "jsonp1343930692" prefix
static NSString* kStringToRemove = #"jsonp1343930692";
str = [str stringByReplacingOccurrencesOfString:kStringToRemove withString:#""];
So in short you have many possibilities depending on what exactly you want to do :)
Of course, once you have removed your strange jsonp1343930692 prefix, you can deserialize your JSON string to obtain a JSON object (either using some third-party lib like SBJSON or using NSJSONSerializer on iOS5 and later, etc)
Have a look at the NSJSONSerialization class to turn this into a Cocoa collection that you can deal with.

Resources