Formatting NSString from NSXMLParser - nsxmlparser

So I have a small project that parses through an XML file. I am trying to format the string so that it has no indents before or after.
Some of the xml is:
<master_url>
<base_url> http://buildmac.ee.ps.edu/~wsn/boin/ </base_url>
<request_task>
<name>request_task</name>
<field>username</field>
</request_task>
...
Before format I have:
2012-04-30 21:42:34.684 XMLParser[33194:b303] string =
http://buildmac.ee.ps.edu/~wsn/boin/
This is how I am trying to format it:
[nodecontent appendString:[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
Afterward, it only contains a blank string "" in nodecontent.
It works for every other element except for that webaddress because it is awkwardly indented
I'm pretty new to Objective C and Xcode so I'm sorry if this is a dumb question, but none of the posts I looked at fixed my issue.

I found out how to make it work. I did it in 3 messages to remove Tabs, New Lines, and Spaces:
string = [[string stringByReplacingOccurrencesOfString: #"\n" withString: #""] mutableCopy];
string = [[string stringByReplacingOccurrencesOfString: #"\t" withString: #""] mutableCopy];
string = [[string stringByReplacingOccurrencesOfString: #" " withString: #""] mutableCopy];
Note: string is an NSMutableString

Related

Remove special characters in NSMutableAttributedString

In my app to show text in CATextLayer(change colors for characters),using NSMutableAttributedString to change colors,i want remove special characters in NSMutableAttributedString to show PopUp view, but didn't know how to remove special characters, to help to solve problem
i want like this type of o/p
"code" to code //in NSMutableAttributedString, not in NSString
to remove such characters you simply write something like this:
NSMutableString* mutableString = ...;
[mutableString replaceOccurrencesOfString:#"\"" withString:#"" options:0 range:NSMakeRange(0, mutableString.length)];
Note that symbol " is written as \" - this one is called an escape sequence.
Here is a list of such special characters in C - http://msdn.microsoft.com/en-us/library/h21280bw(v=vs.80).aspx
Try this...This may help you.
NSMutableString *unfilteredString = #"!##$%^&*()_+|abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
NSCharacterSet *notAllowedChars = [[NSCharacterSet characterSetWithCharactersInString:#"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"] invertedSet];
NSMutableString *resultString = [[unfilteredString componentsSeparatedByCharactersInSet:notAllowedChars] componentsJoinedByString:#""];
NSLog (#"Result: %#", resultString);
You can give try to this may it fits in your code:
NSMutableString *mutableStrng = [NSMutableString stringWithCapacity:1000];
[mutableStrng setString:#"my name is i#pho#ne"];
[mutableStrng replaceOccurrencesOfString:#"#" withString:#"" options:0 range:NSMakeRange(0,
mutableStrng.length)];
NSMutableAttributedString *mutableAtrString = [[NSMutableAttributedString
alloc]initWithString:mutableStrng];

How to remove new line characters from NSString in a webservice response?

I am presently getting a Webservice Response which contains many new line characters. I have tried the following approaches but still i am not able to eliminate the New Line Characters.
1)
responseString = [responseString stringByReplacingOccurrencesOfString:#"\n" withString:#""];
2)
responseString = [responseString stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
3)
NSRange foundRange = [responseString rangeOfString:#"\n"];
if (foundRange.location != NSNotFound)
[responseString stringByReplacingOccurrencesOfString:#"\n"
withString:#""
options:0
range:foundRange];
My Webservice respsonse is in this format.
META NAME="ColdFusionMXEdition" CONTENT="ColdFusion DevNet Edition - Not for Production Use."?
wddxPacket version='1.0'><header/><data><string>{"MESSAGE":"","CODE":1,"RESPONSE":{"FILENAME":"CustomerSkillsIntro","PLAYLIST":[{"TIMEOUT":73,"TITLE":"Greet","QUESTIONNUMBER":1,"TIMEIN":71,"VALIDRESPONSE":1},{"TIMEOUT":77,"TITLE":"Have Name Tag","QUESTIONNUMBER":2,"TIMEIN":74,"VALIDRESPONSE":1},{"TIMEOUT":83,"TITLE":"Greet","QUESTIONNUMBER":3,"TIMEIN":78,"VALIDRESPONSE":1},{"TIMEOUT":112,"TITLE":"Helping Do My Job","QUESTIONNUMBER":4,"TIMEIN":109,"VALIDRESPONSE":1},{"TIMEOUT":134,"TITLE":"Greet Happily","QUESTIONNUMBER":5,"TIMEIN":131,"VALIDRESPONSE":1},{"TIMEOUT":144,"TITLE":"Stay cheerful when resident is crabby","QUESTIONNUMBER":6,"TIMEIN":141,"VALIDRESPONSE":1},{"TIMEOUT":154,"TITLE":"Bond with the new resident","QUESTIONNUMBER":7,"TIMEIN":151,"VALIDRESPONSE":1},...................
My requirement is to capture only the part of the string from {"MESSAGE":"","CODE":1, till the end. But i am getting too many white spaces and new line characters before the required part.
It looks like you could simplify your problem by taking string from first occurance of '{' to last occurance of '}'.
Code below ensures the result you want with different approach. Why go trough the process of removing white space if you say you need only the part "from {"MESSAGE":"","CODE":1, till the end.`"
NSRange start = [responseString rangeOfString:#"{"];
NSRange end = [responseString rangeOfString:#"}" options:NSBackwardsSearch];
NSString *result = nil;
if ((start.location != NSNotFound)&&(start.location != NSNotFound))
{
NSRange resultRange = NSMakeRange(start.location,end.location - start.location + 1);
result = [responseString substringWithRange: resultRange];
NSLog (#"returning with result: %#", result);
}
else
{
NSLog (#"abort mission");
}

How to remove whitespace in a string?

I have a string say "Allentown, pa"
How to remove the white space in between , and pa using objective c?
This will remove all space from myString.
NSString *newString = [myString stringByReplacingOccurrencesOfString:#" " withString:#""];
Here is a proper and documented way of removing white spaces from your string.
whitespaceCharacterSet Apple Documentation for iOS says:
Returns a character set containing only the in-line whitespace characters space (U+0020) and tab (U+0009).
+ (id)whitespaceCharacterSet
Return Value
A character set containing only the in-line whitespace characters space (U+0020) and tab (U+0009).
Discussion
This set doesn’t contain the newline or carriage return characters.
Availability
Available in iOS 2.0 and later.
You can use this documented way:
[yourString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
Hope this helps you.
If you need any more help then please let me know on this.
Probably the solution in one of the answers in Collapse sequences of white space into a single character and trim string:
NSString *whitespaceString = #" String with whitespaces ";
NSString *trimmedString = [whitespaceString stringByReplacingOccurrencesOfString:#" " withString:#""];
If you want to white-space and new-line character as well then use "whitespaceAndNewlineCharacterSet" instead of "whitespaceCharacterSet"
NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
NSString *trimmedString = [temp.text stringByTrimmingCharactersInSet:whitespace];
NSLog(#"Value of the text field is %#",trimmedString);
myStr = [myStr stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *sample = #" string with whitespaces";
NSString *escapeWhiteSpaces = [sample stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
- (NSString *)removeWhitespaces {
return [[self componentsSeparatedByCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]]
componentsJoinedByString:#""];
}
In my case NSString was added Zero Width Space(i i used some library). so solution worked for me.
NSMutableString *newString=[[newString stringByReplacingOccurrencesOfString:#"\u200B" withString:#""] mutableCopy];
#"\u200B" is Zero width space character value.
Here is the proper way to remove extra whitespaces from string which is coming in between.
NSString *yourString = #"Allentown, pa";
NSCharacterSet *whitespaces = [NSCharacterSet whitespaceCharacterSet];
NSPredicate *noEmptyStrings = [NSPredicate predicateWithFormat:#"SELF != ''"];
NSArray *parts = [yourString componentsSeparatedByCharactersInSet:whitespaces];
NSArray *filteredArray = [parts filteredArrayUsingPredicate:noEmptyStrings];
yourString = [filteredArray componentsJoinedByString:#" "];
you can use remove function to remove any substring from the string
- (NSString*)remove:(NSString*)textToRemove fromString:(NSString*)input {
return [input stringByReplacingOccurrencesOfString:textToRemove withString:#""];
}
I have tried all the solutions here, none of them could remove the whitespace generated by the Chinese PinYin Input method.
After some debugging, I found this working:
NSString *newString = [myString stringByReplacingOccurrencesOfString:#"\342\200\206" withString:#""];
I have googled what the '\342\200\206' is, but failed.
Whatever, it works for me.
Hi there is the swift version of the solution with extension :
extension String{
func deleteSpaces() -> String{
return self.stringByReplacingOccurrencesOfString(" ", withString: "")
}
}
And Just call
(yourString as! String).deleteSpaces()
Swift 3:
var word: String = "Hello world"
let removeWhiteSpace = word.stringByRemovingWhitespaces
word = "Helloworld"

How to do a backwards search to find the 2nd space/blank and replace it with another string?

it's me again. I've asked a question similar to this just awhile ago but this question is a bit more complex. I was planning on using RegexKitLite to do what I needed to do but I believe this can be done with out it. I have a NSString that has some words with spaces/blanks in it and I'm wanting to get the very last space in the string that is to the left of the last word. Example String below:
NSString *string = #"Here is an example string HELLO ";
As you can see in the string above there is a space/blank at the very end of the string. I'm wanting to be able to get the space/blank to the left of HELLO and replace it with my own text/string. I'm working on using the NSString's NSBackwardsSearch but it's not working.
NSString *spaceReplacement = #"text that i want";
NSString *replaced = [snipet [string rangeOfString:substring options:NSBackwardsSearch].location:#" " withString:spaceReplacement];
NSLog(#"%#", replaced);
Any help would help, I'm just tired of trying to fix this thing, it's driving me bonkers. I thought I could do this with RegexKitLite but the learning curve for that is too steep for me considering my timeframe I'm working with. I'm glad Jacob R. referred me to use NSString's methods :-)
This solution assumes you always have a space at the end of your string... it should convert
Here is an example string HELLO
... to:
Here is an example stringtext that i wantHELLO
... since that's what I understood you wanted to do.
Here's the code:
NSString *string = #"Here is an example string HELLO ";
NSRange rangeToSearch = NSMakeRange(0, [string length] - 1); // get a range without the space character
NSRange rangeOfSecondToLastSpace = [string rangeOfString:#" " options:NSBackwardsSearch range:rangeToSearch];
NSString *spaceReplacement = #"text that i want";
NSString *result = [string stringByReplacingCharactersInRange:rangeOfSecondToLastSpace withString:spaceReplacement];
The trick is to use the [NSString rangeOfString:options:range:] method.
Note: If the string doesn't always contain a space at the end, this code will probably fail, and you would need code that is a bit more complicated. If that is the case, let me know and I'll update the answer.
Disclaimer: I haven't tested the code, but it should compile and work just fine.
Something like this should work:
NSString *string = #"Here is an example string HELLO ";
if ([string hasSuffix:#" "]) {
NSString *spaceReplacement = #"text that i want";
NSString *replacedString = [[string substringToIndex:
[string length]] stringByAppendingString:spaceReplacement];
NSLog(#"replacedString == %#", replacedString);
}
To solve #Senseful note
If the string doesn't always contain a space at the end, this code will probably fail, and you would need code that is a bit more complicated. If that is the case, let me know and I'll update the answer.
I had added one line into code that helps in such situations and make code more universal:
// Some income sting
NSString * string = #"Here is an example string HELLO ";
// clear string from whitespace in end on string
[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSRange rangeToSearch = NSMakeRange(0, [string length]);
NSRange rangeOfSecondToLastSpace = [string rangeOfString:#" "
options:NSBackwardsSearch
range:rangeToSearch];
// Replaed with String
NSString * spaceReplacement = #"text that i want";
NSString * result = [string stringByReplacingCharactersInRange:rangeOfSecondToLastSpace
withString:spaceReplacement];

Replace a char into NSString

I want simply replace all occourrencies of "+" with a blank " " char...
I tried some sample listed here, also used NSSMutableString, but the program crash...
what's the best way to replace a char from another??
thanks
If you want to replace with a mutable string (NSMutableString) in-place:
[theMutableString replaceOccurrencesOfString:#"+"
withString:#" "
options:0
range:NSMakeRange(0, [theMutableString length])]
If you want to create a new immutable string (NSString):
NSString* newString = [theString stringByReplacingOccurrencesOfString:#"+"
withString:#" "];
NSString *firstString = #"I'm a noob at Objective-C", *finalString;
finalString = [[firstString stringByReplacingOccurrencesOfString:#"O" withString:#"0"] stringByReplacingOccurrencesOfString:#"o" withString:#"0"];
Got the code from here!