Removing last digit from a string containing numbers - ios

I simply need to remove the last digit from a string that contains numbers.
Say that my mutable string is named scannedItem and produces the following 038000768625.
How can I remove the last digit, and put it into a new string that produces 03800076862?
Thanks

Create a new string from old one. Firstly by removing last character
NSString *newString = [scannedItem substringToIndex:[scannedItem length]-1];
Now append
//Append string of your choice
newString = [newString stringByAppendingString:#"?"];

Related

Check if String contains alphanumeric

I want to check the string if it contains alphanumeric only.(Both letters and number only).
I tried using NSCharacterSet *strCharSet = [NSCharacterSet characterSetWithCharactersInString:#"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"];
I also tried this NSString *string = #"[^a-zA-Z0-9]"; = no luck
but it only checks if the string does not contain any characters or it contains only this characters. I need to required the user to put both letters and numbers.
-update
I have a textfield for password. I need the user to input both letters and password. But I can't check if the textfield contains BOTH letters and numbers. By using the code above, it only checks if the textfield's text contains only alphanumeric.
You just need to make your checks for numbers and letters separate.
BOOL containsLetter = NSNotFound != [input rangeOfCharacterFromSet:NSCharacterSet.letterCharacterSet].location;
BOOL containsNumber = NSNotFound != [input rangeOfCharacterFromSet:NSCharacterSet.decimalDigitCharacterSet].location;
NSLog(#"Contains letter: %d\n Contains number: %d", containsLetter, containsNumber);

Splitting a string into an array, where individual items may contain the delimiter

Suppose I have an NSString object that contains a list. Included in the list are some quotes, which contain the separator character. How best to split this up into an array?
An example would be a list of names and email addresses, separated by commas:
"Bar, Foo" <foo#bar.com>, "Blow, Joe" <joe#Blow.com>
I found a solution, but I'm wondering if maybe there's a more efficient solution. My solution was basically this:
First, parse into a mutable array the string by quote marks.
For array items with odd indexes, change the commas to tokens.
Merge the mutable array back into a string.
Parse the new string into an array using -componentsSeparatedByString.
Loop through the array, replacing the tokens with commas.
It seems like there should be an NSString method that does this, but I didn't find one.
For what it's worth, here's my solution:
-(NSArray *)listFromString:(NSString *)originalString havingQuote:(NSString *)quoteChar separatedByDelimiter:(NSString *)delimiter {
// First we need to parse originalString to replace occurrences of the delimiter with tokens.
NSMutableArray *arrayOfQuotes = [[originalString componentsSeparatedByString:quoteChar] mutableCopy];
for (int i=1; i<[arrayOfQuotes count]; i +=2) {
//Replace occurrences of delimiter with a token
NSString *stringToMassage = arrayOfQuotes[i];
stringToMassage = [stringToMassage stringByReplacingOccurrencesOfString:delimiter withString:#"~~token~~"];
arrayOfQuotes[i] = stringToMassage;
}
NSString *massagedString = [[arrayOfQuotes valueForKey:#"description"] componentsJoinedByString:quoteChar];
// Now we have a string with the delimiters replaced by tokens.
// Next we divide the string by the delimeter.
NSMutableArray *massagedArray = [[massagedString componentsSeparatedByString:delimiter] mutableCopy];
// Finally, we replace the tokens with the quoteChar
for (int i=0; i<[massagedArray count]; i++) {
NSString *thisItem = massagedArray[i];
thisItem = [thisItem stringByReplacingOccurrencesOfString:#"~~token~~" withString:delimiter];
massagedArray[i] = thisItem;
}
return [massagedArray copy];
}
It's not NSString you should be looking at, but NSScanner. Create an NSScanner that will parse the NSString the way you want. If you know that certain characters will never occur, you can change commas between quotes to one of those characters, then explode the string into an array, then replace the temporary character with a comma. You can probably create an NSScanner that will do all the parsing if you really get into it.

basic programming concept: when to initialize new string versus just creating new variable

So I've been programming for a year but this concept still trips me up sometimes. My understanding is that if you don't initialize and allocate a new object when you create a new variable name using the pointer operator '*' that the danger is that the value of that new variable will always just be tied to whatever memory address it is you've pointed the name. For example, in #2 if string is set to '6' because array[1] is set to '6' but later the value of element #1 in array changes to '7' then string will return 7. But if I used method 1 where I use a string class method to allocate and initialize a memory address of its own for string then string would stay '6' even if later element #1 is changed to hold a value of '7'. Is this right?
What’s the difference between:
NSString *string = [NSString stringwithstring: array[1]];
AND
NSString *string = array[1];
As a sidenote: I have a tough time understanding how this will matter much because if array is immutable then the only way it could be changed is if a new array is initialized and reallocated with a different value for element #1. Also, once my view controller gets popped off of the stack when the user continues to navigate through my app, if it gets called again all of these objects will get recreated from scratch- so it usually won't matter. But I just want to make sure I am getting the concept anyways.
Actually, whether you use the 1st or 2nd option has nothing to do with the array itself.
The 2nd option would not result in any change even if the array was mutable and you replaced the object at index 1. string would still point to the original object.
In the example you've given, the choice of the two options only matters if in reality, the string you get from the array is an NSMutableString. If the string is an immutable NSString then either option gives the same result. But if you actually have a mutable NSMutableString, then option 2 means that your string value can change over time of another reference to the mutable string makes changes to the string.
Example:
NSMutableString *mutable = [NSMutableString stringWithString:#"hello"];
NSArray *array = #[ #"stuff", mutable ];
NSString *string1 = [NSString stringWithString:array[1]];
NSString *string2 = array[1];
NSLog(#"string1 = %#, string2 = %#", string1, string2);
[mutable appendString:#" there"];
NSLog(#"string1 = %#, string2 = %#", string1, string2);
The log output will be:
string1 = hello, string2 = hello
string1 = hello, string2 = hello there
See how string2 was changed as a result of modifying mutable.
(edit: per martin R's comment--suppose the strings in the example are mutable strings)
I made a diagram to help explain what's going on.
The first diagram is your initial setup. string = nil and you have a string reference in array[1].
1) do string = array[1]. Now string and array[1] point to the same string object.
2a) alternately, as in 2a, you can do string = [ NSString stringWithString:array[1]]... This will point string to a copy of the string in array[1]
Notice in all cases if you mutate the array, string still contains a reference to either a) the original string from array[1] or the copy you created.
2b) For example, let's do array[1] = #"test". [string description] will still return ABC
HTH
Your string pointer does not remember where the string was at the time you assigned it, so array-level changes don't matter.
The practical difference is about what happens if your array actually contains mutable strings instead of plain ones. Your first example creates a new string that has the content that's at array[1] when the assignment takes place. In your second example, the thing pointed to by string could be different moment-to-moment if some other code changed the underlying mutable string that's in array[1] at assignment time.

How to remove characters from string when string length is unknown

I am taking input from textfield ,i has to extract the characters more than length 5. Then how to remove characters from text
You can try this,
if(level_label.text.length>20)
{
NSString *str=[level_label.text substringFromIndex:20];
// Place str in next_label.text
}

Objective-C - Remove last character from string

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];
...

Resources