Removing the front character from NSMutableString - objective-c

I am trying to remove the front character of a NSMutableString and have tried:
[str setString: [str substringFromIndex:1]] ,
[str deleteCharactersInRange:NSMakeRange(0,1)]
and a few others. These two either remove every character or every character except for the one I am trying to remove so for example if I have the String "-2357" and am trying to remove the "-" then I get just the "-" when I should get "2357".
Am I doing something wrong, and how can I fix this?

If you want to use the deleteCharactersInRange method, do this
NSRange range = {0,1};
[str deleteCharactersInRange:range];
Or, you could use substringFromIndex like so:
str = [str substringFromIndex:1];
Contrary to what you are saying, [str deleteCharactersInRange:NSMakeRange(0,1)] should work fine, I don't know why that is not working.
[str substringToIndex:1] will return the string from the beginning to the index 1, which is -. What you want is substringFromIndex. And as this method returns a NSString, you will need to assign it to str; just calling the method on str is not enough.
Edit
Using the deleteCharactersInRange may pose problems for some type of characters. For more information refer to this a question here.
Instead, you can safely use
[str deleteCharactersInRange:[str rangeOfComposedCharacterSequenceAtIndex:0]]

instead of:
[str substringToIndex:1]
Do this:
[str substringFromIndex:1]

If you want to remove first character of the string you can use this:-
string = [string substringFromIndex:1];

Related

Split NSString into words, then rejoin it into original form

I am splitting an NSString like this: (filter string is an nsstring)
seperatorSet = [NSMutableCharacterSet whitespaceAndNewlineCharacterSet];
[seperatorSet formUnionWithCharacterSet:[NSCharacterSet punctuationCharacterSet]];
NSMutableArray *words = [[filterString componentsSeparatedByCharactersInSet:seperatorSet] mutableCopy];
I want to put words back into the form of filter string with the original punctuation and spacing. The reason I want to do this is I want to change some words and put it back together as it was originally.
A more robust way to split by words is to use string enumeration. A space is not always the delimiter and not all languages delimit spaces anyway (e.g. Japanese).
NSString * string = #" \n word1! word2,%$?'/word3.word4 ";
[string enumerateSubstringsInRange:NSMakeRange(0, string.length)
options:NSStringEnumerationByWords
usingBlock:
^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
NSLog(#"Substring: '%#'", substring);
}];
// Logs:
// Substring: 'word1'
// Substring: 'word2'
// Substring: 'word3'
// Substring: 'word4'
NSString *myString = #"Foo Bar Blah B..";
NSArray *myWords = [myString componentsSeparatedByCharactersInSet:
[NSCharacterSet characterSetWithCharactersInString:#" "]
];
NSString* string = [myWords componentsJoinedByString: #" "];
NSLog(#"%#",string);
Since you eliminate the original punctuation, there's no way to turn it back automatically.
The only way is not to use componentsSeparatedByCharactersInSet.
An alternative solution may be to iterate through the string and, for each char, check if it belongs to your character set.
If yes, add the char to a list and the substring to another list (you may use NSMutableArray class).
This way, for example, you know that the punctuation char between the first and the second substring is the first character in your list of separators.
You can use the pathArray componentsJoinedByString: method of the array class to rejoin the words:
NSString *orig = [words pathArray componentsJoinedByString:#" "];
How are you determining which words need to be replaced? Instead of breaking it apart in the first place, perhaps using -stringByReplacingOccurrencesOfString:withString:options:range: would be more suitable.
My guess is you may not be using the best API. If you're really worried about words, you should be using a word-based API. I'm a bit hazy on whether that would be NSDataDetector or something else. (I believe NSRegularExpression can deal with word boundaries in a smarter way.)
If you are using Mac OS X 10.7+ or iOS 4+ you can use NSRegularExpression, The pattern to replace a word is: "\b word \b" - (no spaces around word) \b matches a word boundary. Look at methods replaceMatchesInString:options:range:withTemplate: and stringByReplacingMatchesInString:options:range:withTemplate:.
Under 10.6 pr earlier if you wish to use regular expressions you can wrap the regcomp/regexec C-based functions, they support word boundaries as well. However you may prefer to use one of the other Cocoa options mentioned in other answers for this simple case.

Random uppercase - lowercase

I'd like to let a string change letters to lowercase or uppercase randomly(in Xcode).
for example: "example" to "ExaMpLe" or "eXAMPle" or ExAmPlE" or something else like this randomly..
hot can i solve this?
thanks
You could either use the -uppercaseString and -lowercaseString methods on substrings, or use the toupper() and tolower() functions on characters. There's no way to simply filter a string; you'll want to use either an NSMutableString or a C array of characters.
See this question for how to get a random boolean value, which you can use to decide whether a character should be uppercase or lowercase.
NSString has both a lowercaseString and uppercaseString method. You can iterate over the characters in a string as a sequence of substrings, using some random source to call the appropriate lower/upper case on each of them, collecting the result. Something like...
NSMutableString result = [NSMutableString string];
for (NSUInteger i = 0; i < [myString length]; i++)
{
NSString *substring = [myString substringWithRange:NSMakeRange(i, 1)];
[result appendString:(rand() % 2) ? [substring lowercaseString]
: [substring uppercaseString]];
}
You may prefer a better source of entropy than rand, but it'll do for an example (don't forget to seed it if you use this case as is). If the strings are large, you can do it in-place on an NSMutableString.
You could break the word into an array of letters, and loop over this using a random number to determining case, after looping the array, simply stick the letters back together using NSMutableString.
NSString had a uppercaseString and lowercaseString methods you can use.

Replacing one character in a string in Objective-C

Hoping somebody can help me out - I would like to replace a certain character in a string and am wondering what is the best way to do this?
I know the location of the character, so for example, if I want to change the 3rd character in a string from A to B - how would I code that?
If it is always the same character you can use:
stringByReplacingOccurrencesOfString:withString:
If it is the same string in the same location you can use:
stringByReplacingOccurrencesOfString:withString:options:range:
If is just a specific location you can use:
stringByReplacingCharactersInRange:withString:
Documentation here:
https://developer.apple.com/documentation/foundation/nsstring
So for example:
NSString *someText = #"Goat";
NSRange range = NSMakeRange(0,1);
NSString *newText = [someText stringByReplacingCharactersInRange:range withString:#"B"];
newText would equal "Boat"
NSString *str = #"123*abc";
str = [str stringByReplacingOccurrencesOfString:#"*" withString:#""];
//str now 123abc
Here is the code:
[aString stringByReplacingCharactersInRange:NSMakeRange(3,1) withString:#"B"];
Use the replaceCharactersInRange: withString: message on a NSMutableString object.

How to get a single NSString character from an NSString

I want to get a character from somewhere inside an NSString. I want the result to be an NSString.
This is the code I use to get a single character at index it:
[[s substringToIndex:i] substringToIndex:1]
Is there a better way to do it?
This will also retrieve a character at index i as an NSString, and you're only using an NSRange struct rather than an extra NSString.
NSString * newString = [s substringWithRange:NSMakeRange(i, 1)];
If you just want to get one character from an a NSString, you can try this.
- (unichar)characterAtIndex:(NSUInteger)index;
Used like so:
NSString *originalString = #"hello";
int index = 2;
NSString *theCharacter = [NSString stringWithFormat:#"%c", [originalString characterAtIndex:index-1]];
//returns "e".
Your suggestion only works for simple characters like ASCII. NSStrings store unicode and if your character is several unichars long then you could end up with gibberish. Use
- (NSRange)rangeOfComposedCharacterSequenceAtIndex:(NSUInteger)index;
if you want to determine how many unichars your character is. I use this to step through my strings to determine where the character borders occur.
Being fully unicode able is a bit of work but depends on what languages you use. I see a lot of asian text so most characters spill over from one space and so it's work that I need to do.
NSMutableString *myString=[NSMutableString stringWithFormat:#"Malayalam"];
NSMutableString *revString=#"";
for (int i=0; i<myString.length; i++) {
revString=[NSMutableString stringWithFormat:#"%c%#",[myString characterAtIndex:i],revString];
}
NSLog(#"%#",revString);

How to remove first 3 characters from NSString?

I have a string like this "A. rahul VyAs"
and i want to remove "A. " and the space after the "A." so that new string would be "rahul VyAs"
How do i achieve this?
You can use the NSString instance methods substringWithRange: or substringFromIndex:
NSString *str = #"A. rahul VyAs";
NSString *newStr = [str substringWithRange:NSMakeRange(3, [str length]-3)];
or
NSString *str = #"A. rahul VyAs";
NSString *newStr = [str substringFromIndex:3];
This is a solution I have seen specifically for removing regularly occurring prefixes and solving the answer to the question How do I remove "A. "?
NSString * name = #"A. rahul VyAs";
NSString * prefixToRemove = #"A. ";
name = [name stringByReplacingOccurrencesOfString:prefixToRemove withString:#""];
This code will remove what you tell it to remove/change if the character set exists, such as "A. ", even if the three characters (or more/less) are in the middle of the string.
If you wanted to remove rahul, you can. It's diverse in that you specify exactly what you want removed or changed, and if it exists anywhere in the String, it will be removed or changed.
If you only want a certain specified number of characters removed from the front of the text that are always random or unknown, use the [string length] method as is the top answer.
If you want to remove or change certain characters that repeatedly appear, the method I have used will enable that, similar to Wordsearch on document editors.
Try this,
char *string=[#"A. rahul VyAs" cStringUsingEncoding:NSUTF8StringEncoding];
char *subString=&name[3];
NSString *newString=[NSString stringWithCString:subString encoding:NSUTF8StringEncoding];
It's this simple:
myString = [myString subStringFromIndex:3]
That's it.