Replacing one character in a string in Objective-C - 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.

Related

How to omit a certain substring out of an NSString?

I would like to know how it is possible to omit a specific substring out an NSString, assuming the NSString does contain that substring.
For example:
Original string: "This is a string but these words should be omitted."
Substring to omit: "but these words should be omitted".
Result string: "This is a string."
Thanks ahead,
iLyrical.
NSString *originalString = #"This is a string but these words should be omitted.";
NSString *substringToOmit = #" but these words should be omitted";
NSString *resultString = [originalString stringByReplacingOccurencesOfString:substringToOmit
withString:#""];
See NSString's stringByReplacingOccurrencesOfString:withString:. You may also want to trim the trailing whitespace with stringByTrimmingCharactersInSet:.

Finding a substring in a NSString object

I have an NSString object and I want to make a substring from it, by locating a word.
For example, my string is: "The dog ate the cat", I want the program to locate the word "ate" and make a substring that will be "the cat".
Can someone help me out or give me an example?
Thanks,
Sagiftw
NSRange range = [string rangeOfString:#"ate"];
NSString *substring = [[string substringFromIndex:NSMaxRange(range)] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSString *str = #"The dog ate the cat";
NSString *search = #"ate";
NSString *sub = [str substringFromIndex:NSMaxRange([str rangeOfString:search])];
If you want to trim whitespace you can do that separately.
What about this way?
It's nearly the same.
But maybe meaning of NSRange easier to understand for beginners, if it's written this way.
At last, it's the same solution of jtbandes
NSString *szHaystack= #"The dog ate the cat";
NSString *szNeedle= #"ate";
NSRange range = [szHaystack rangeOfString:szNeedle];
NSInteger idx = range.location + range.length;
NSString *szResult = [szHaystack substringFromIndex:idx];
Try this one..
BOOL isValid=[yourString containsString:#"X"];
This method return true or false. If your string contains this character it return true, and otherwise it returns false.
NSString *theNewString = [receivedString substringFromIndex:[receivedString rangeOfString:#"Ur String"].location];
You can search for a string and then get the searched string into another string...
-(BOOL)Contains:(NSString *)StrSearchTerm on:(NSString *)StrText
{
return [StrText rangeOfString:StrSearchTerm options:NSCaseInsensitiveSearch].location==NSNotFound?FALSE:TRUE;
}
You can use any of the two methods provided in NSString class, like substringToIndex: and substringFromIndex:. Pass a NSRange to it as your length and location, and you will have the desired output.

How to check if NSString begins with a certain character

How do you check if an NSString begins with a certain character (the character *).
The * is an indicator for the type of the cell, so I need the contents of this NSString without the *, but need to know if the * exists.
You can use the -hasPrefix: method of NSString:
Objective-C:
NSString* output = nil;
if([string hasPrefix:#"*"]) {
output = [string substringFromIndex:1];
}
Swift:
var output:String?
if string.hasPrefix("*") {
output = string.substringFromIndex(string.startIndex.advancedBy(1))
}
You can use:
NSString *newString;
if ( [[myString characterAtIndex:0] isEqualToString:#"*"] ) {
newString = [myString substringFromIndex:1];
}
hasPrefix works especially well.
for example if you were looking for a http url in a NSString, you would use componentsSeparatedByString to create an NSArray and the iterate the array using hasPrefix to find the elements that begin with http.
NSArray *allStringsArray =
[myStringThatHasHttpUrls componentsSeparatedByString:#" "]
for (id myArrayElement in allStringsArray) {
NSString *theString = [myArrayElement description];
if ([theString hasPrefix:#"http"]) {
NSLog(#"The URL is %#", [myArrayElement description]);
}
}
hasPrefix returns a Boolean value that indicates whether a given string matches the beginning characters of the receiver.
- (BOOL)hasPrefix:(NSString *)aString,
parameter aString is a string that you are looking for
Return Value is YES if aString matches the beginning characters of the receiver, otherwise NO. Returns NO if aString is empty.
As a more general answer, try using the hasPrefix method. For example, the code below checks to see if a string begins with 10, which is the error code used to identify a certain problem.
NSString* myString = #"10:Username taken";
if([myString hasPrefix:#"10"]) {
//display more elegant error message
}
Use characterAtIndex:. If the first character is an asterisk, use substringFromIndex: to get the string sans '*'.
NSString *stringWithoutAsterisk(NSString *string) {
NSRange asterisk = [string rangeOfString:#"*"];
return asterisk.location == 0 ? [string substringFromIndex:1] : string;
}
Another approach to do it..
May it help someone...
if ([[temp substringToIndex:4] isEqualToString:#"http"]) {
//starts with http
}
This might help? :)
http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/characterAtIndex:
Just search for the character at index 0 and compare it against the value you're looking for!
This nice little bit of code I found by chance, and I have yet to see it suggested on Stack. It only works if the characters you want to remove or alter exist, which is convenient in many scenarios. If the character/s does not exist, it won't alter your NSString:
NSString = [yourString stringByReplacingOccurrencesOfString:#"YOUR CHARACTERS YOU WANT TO REMOVE" withString:#"CAN either be EMPTY or WITH TEXT REPLACEMENT"];
This is how I use it:
//declare what to look for
NSString * suffixTorRemove = #"</p>";
NSString * prefixToRemove = #"<p>";
NSString * randomCharacter = #"</strong>";
NSString * moreRandom = #"<strong>";
NSString * makeAndSign = #"&amp;";
//I AM INSERTING A VALUE FROM A DATABASE AND HAVE ASSIGNED IT TO returnStr
returnStr = [returnStr stringByReplacingOccurrencesOfString:suffixTorRemove withString:#""];
returnStr = [returnStr stringByReplacingOccurrencesOfString:prefixToRemove withString:#""];
returnStr = [returnStr stringByReplacingOccurrencesOfString:randomCharacter withString:#""];
returnStr = [returnStr stringByReplacingOccurrencesOfString:moreRandom withString:#""];
returnStr = [returnStr stringByReplacingOccurrencesOfString:makeAndSign withString:#"&"];
//check the output
NSLog(#"returnStr IS NOW: %#", returnStr);
This one line is super easy to perform three actions in one:
Checks your string for the character/s you do not want
Can replaces them with whatever you like
Does not affect surrounding code
NSString* expectedString = nil;
if([givenString hasPrefix:#"*"])
{
expectedString = [givenString substringFromIndex:1];
}

Position of a character in a NSString or NSMutableString

I have searched for hours now and haven't found a solution for my problem. I have a NSString which looks like the following:
"spacer": ["value1", "value2"], "spacer": ["value1", "value2"], ...
What I want to do is to remove the [ ] characters from the string. It's seems to be impossible with objective-c. Most other programming languages offer functions like strpos or indexOf which allow me to search for a character or string and locate the position of it. But there seems nothing to be like this in objective-c.
Does anyone has an idea on how to remove these characters?
Additionally there are [] characters in the string which should remain, so I can't just use NSMutableString stringByReplacingOccurencesOfString:withString. I need to search first for the spacer string and then remove only the next two [] chars.
Thank you for helping me.
To find occurrences of a string within a string, use the rangeOfXXX methods in the NSString class. Then you can construct NSRanges to extract substrings, etc.
This example removes only the first set of open/close brackets in your sample string...
NSString *original = #"\"spacer\": \[\"value1\", \"value2\"], \"spacer\": \[\"value1\", \"value2\"]";
NSLog(#"%#", original);
NSRange startRange = [original rangeOfString:#"\["];
NSRange endRange = [original rangeOfString:#"]"];
NSRange searchRange = NSMakeRange(0, endRange.location);
NSString *noBrackets = [original stringByReplacingOccurrencesOfString:#"\[" withString:#"" options:0 range:searchRange];
noBrackets = [noBrackets stringByReplacingOccurrencesOfString:#"]" withString:#"" options:0 range:searchRange];
NSLog(#"{%#}", noBrackets);
The String Programming Guide has more details.
You might alternatively also be able to use the NSScanner class.
This worked for me to extract everything to the index of a character, in this case '[':
NSString *original = #"\"spacer\": \[\"value1\", \"value2\"], \"spacer\": \[\"value1\", \"value2\"]";
NSRange range = [original rangeOfString:#"\["];
NSString *toBracket = [NSString stringWithString :[original substringToIndex:range.location] ];
NSLog(#"toBracket: %#", toBracket);

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.