Objective C - How to compare string from the console - ios

My code always returns "fail" for the following string comparison using isEqualToString. What is the correct way to compare strings coming from the console?
char buf[MAX_LENGTH];
fgets(buf, MAX_LENGTH, stdin);
NSString *s = [[NSString alloc] initWithUTF8String:buf];
NSLog(#"You typed %#", s);
NSString *n = #"exit";
if ([n isEqualToString:s]) {
NSLog(#"success!");
} else {
NSLog(#"fail");
}

The result of fgets contains "\n", So you need define your "n" as this:
NSString *n = #"exit\n";
Or remove the "\n" from "s":
NSString *s = [[NSString alloc] initWithUTF8String:buf];
s = [s stringByReplacingOccurrencesOfString:#"\n" withString:#""];

Related

How to convert HEX to NSString in Objective-C j?

I have a NSString with hex string like "&# x62a;&# x631;&# x642;&# x628;" which means "ترقب".
Now I want to convert the hex string into another NSString object which shows "ترقب". How to do that ?
- (NSMutableString *) hextostring:(NSString *) str{
//ت
NSMutableString *string = [[NSMutableString alloc]init];
str = [str stringByReplacingOccurrencesOfString:#"&#" withString:#"0"];
str = [str stringByReplacingOccurrencesOfString:#" " withString:#"z;"];
NSArray *arr = [str componentsSeparatedByString:#";"];
for (int i =0; i<[arr count]; i++) {
if ([[arr objectAtIndex:i] isEqualToString:#"z"]) {
[string appendString:#" "];
} else {
unsigned x;
[[NSScanner scannerWithString: [arr objectAtIndex:i]] scanHexInt: &x];
[string appendFormat:#"%C",(unichar)x];
}
}
NSLog(#"%#",string);
return string;
}
Your string looks like HTML escape sequences, except for the spaces after the #'s. If this is really what you have (check something isn't just displaying Unicode as escapes) then there is a myriad of ways to convert it. You can just process the string picking out the hex chars and producing UniChar values from them, etc.
If you want a high-level, maybe somewhat long-winded approach, you and try:
- (NSString *)decodeHTMLescapes:(NSString *)raw
{
NSString *nospaces = [raw stringByReplacingOccurrencesOfString:#" " withString:#""]; // one way to remove the spaces
const char *cString = [nospaces UTF8String]; // C string
NSData *bytes = [[NSData alloc] initWithBytesNoCopy:(void *)cString length:strlen(cString) freeWhenDone:NO]; // as bytes
NSAttributedString *attributed = [[NSAttributedString alloc] initWithHTML:bytes documentAttributes:nil]; // interpret as HTML
NSString *decoded = attributed.string; // and finally as plain text
return decoded;
}
That (a) strips the spaces, (b) creates a C string and (c) creates a byte buffer, all that so we can (d) interpret that byte buffer as HTML, and (e) finally gets the string back. The use of initWithBytesNoCopy:length:freeWhenDone: is to reduce the copying all this does.
Use it like:
NSString *raw = #"&# x62a;&# x631;&# x642;&# x628;";
NSString *decoded = [self decodeHTMLescapes:raw];
NSLog(#"%# -> %#", raw, decoded);
HTH

Special Character to Original string - Objective C

I have tried the string(contain special character) to original String. The string received from service. I tried many codes. But i cant get the original String.
i tried the following code
// \U00e0\U00ae\U0089\U00e0\U00ae\U00b2\U00e0\U00ae\U0095\U00e0\U00ae\U00ae\U00e0\U00af\U008d
NSString *name2escaped = #"\\U00e0\\U00ae\\U0089\\U00e0\\U00ae\\U00b2\\U00e0\\U00ae\\U0095\\U00e0\\U00ae\\U00ae\\U00e0\\U00af\\U008d";
NSString *name2 = [NSString stringWithCString:[name2escaped cStringUsingEncoding:NSUTF8StringEncoding] encoding:NSNonLossyASCIIStringEncoding];
NSLog(#"name2 = %#", name2);
inputvalue.stringValue = name2;
NSLog (#"%#",name2);
Output prints: à®à®²à®à®®à¯
I worked in Mac OS X development 10.9 Mavericks
Service sometimes send chinese character also. Can anybody help me
As according to your requirement output should be Tamil or Chinese or English Language
Change NSNonLossyASCIIStringEncoding to NSUTF16StringEncoding :
NSString *name2escaped = #"\\U00e0\\U00ae\\U0089\\U00e0\\U00ae\\U00b2\\U00e0\\U00ae\\U0095\\U00e0\\U00ae\\U00ae\\U00e0\\U00af\\U008d";
NSString *name2 = [NSString stringWithCString:[name2escaped cStringUsingEncoding:NSUTF8StringEncoding] encoding:NSUTF16StringEncoding];
NSLog(#"name2 = %#", name2);
Output is : name2 = 屵〰攰屵〰慥屵〰㠹屵〰攰屵〰慥屵〰戲屵〰攰屵〰慥屵〰㤵屵〰攰屵〰慥屵〰慥屵〰攰屵〰慦屵〰㡤 –
I did it
My code is
- (NSString *) OrigninalString:(NSString *)getfilername
{
const char *c;
NSString *name2escaped = [NSString stringWithFormat:#"%#",getfilername];
NSString *string = [NSString
stringWithCString:[name2escaped cStringUsingEncoding:NSUTF8StringEncoding]
encoding:NSNonLossyASCIIStringEncoding];
c = [string cStringUsingEncoding:NSISOLatin1StringEncoding];
if (!c) {
c = [name2escaped cStringUsingEncoding:NSISOLatin1StringEncoding];
}
NSString *newString = [NSString stringWithCString:c encoding:NSUTF8StringEncoding];
c = nil;
string = nil;
return newString;
}

How to replace special characters in NSString with unknown index

I am trying to replace some characters with unknown index like this(i need to replace this Ă,Ŏ,Ĭ,ă,ŏ,ĭ and my input nsstring can be anything):
(void)repairText:(NSString *)textToRepair{`
NSString *pom = textToRepair;`
int pomNum = [pom length];
NSLog(#"Input nsstring: %#",pom);
for (int a = 0; a<pomNum; a++) {
NSString *pomChar, *pomChar2;
pomChar = [pom substringFromIndex:a];
pomChar2 = [pomChar substringToIndex:(1)];
NSLog(#"Char to repair: %#",pomChar2);
if ([pomChar2 isEqual: #"Ă"] || [pomChar2 isEqual:#"Ŏ"] || [pomChar2 isEqual:#"Ĭ"] || [pomChar2 isEqual:#"ă"] || [pomChar2 isEqual:#"ŏ"] || [pomChar2 isEqual:#"ĭ"]) {
if ([pomChar2 isEqual:#"Ă"]) {
NSLog(#"Wrong big a");
}
if ([pomChar2 isEqual:#"Ŏ"]) {
NSLog(#"Wrong big o");
}
if ([pomChar2 isEqual:#"Ĭ"]) {
NSLog(#"Wrong big i");
}
if ([pomChar2 isEqual:#"ă"]) {
NSLog(#"Wrong small a");
}
if ([pomChar2 isEqual:#"ŏ"]) {
NSLog(#"Wrong small o");
}
if ([pomChar2 isEqual:#"ĭ"]) {
NSLog(#"Wrong small i");
}
} else {
NSLog(#"Good");
}
}
pom = [textToRepair stringByReplacingOccurrencesOfString:#"•" withString:#" kulka "];
pom = [textToRepair stringByReplacingOccurrencesOfString:#"¥" withString:#" jen "];
pom = [textToRepair stringByReplacingOccurrencesOfString:#"£" withString:#" libra "];
pom = [textToRepair stringByReplacingOccurrencesOfString:#"€" withString:#" euro "];
[self synthesize:pom];
}
But I am having trouble with 'if'. If anyone know about this, please help in this regard.
NSString *str=#"ĂdsdaĬsd";
str=[str stringByReplacingOccurrencesOfString:#"Ă" withString:#""];
str=[str stringByReplacingOccurrencesOfString:#"Ĭ" withString:#""];
NSLog(#"%#",str);
O/p :dsdasd
NSString has functions to do that for you. dataUsingEncoding:allowLossyConversion: is the method you need.
From the documentation:
- (NSData *)dataUsingEncoding:(NSStringEncoding)encoding allowLossyConversion:(BOOL)flag
If flag is YES and the receiver can’t be converted without losing some information, some characters may be removed or altered in conversion. For example, in converting a character from NSUnicodeStringEncoding to NSASCIIStringEncoding, the character ‘Á’ becomes ‘A’, losing the accent.
Sample code:
NSString *str = #"á, é, í, ó, ú, ü, ñ";
NSData *asciiStringData = [str dataUsingEncoding:NSASCIIStringEncoding
allowLossyConversion:YES];
NSString *finalString = [[NSString alloc] initWithData:asciiStringData
encoding:NSASCIIStringEncoding];
The final string will be : a, e, i, o, u, u, n
NSString * textToRepair = #"Your String";
textToRepair =[textToRepair stringByReplacingOccurrencesOfString:#"•" withString:#"kulka"];
textToRepair =[textToRepair stringByReplacingOccurrencesOfString:#"¥" withString:#"jen"]
textToRepair =[textToRepair stringByReplacingOccurrencesOfString:#"£" withString:#"libra"];
textToRepair =[textToRepair stringByReplacingOccurrencesOfString:#"€" withString:#"euro"];;
and now textToRepair is your output string with changes.
You can used this:
NSString * myString = #"Hello,";
NSString * newString = [myString stringByReplacingOccurrencesOfString:#"," withString:#""];
NSLog(#"%#xx",newString);
I hope this is used full to you.

Objective c Split String Issue

I'm trying to split a string into an NSArray, however I'm having an issue ignoring strings that have speech marks in.
For example
NSString *example = #"100 200 300 \"TEST ITEM\" 500";
NSArray *array = [example componentsSeparatedByString:#" "];
However the array obviously gets created as 100, 100, 300, "Test, ITEM", 500. Is it possible to treat anything with " " as one?
Thanks
You could use a well known CSV Parser which can be configured to use spaces as separators, and will treat double-quotes correctly. That assumes you want usual CSV-handling like escaping of double-quotes inside double-quoted strings, etc.
Otherwise, you'll probably need to write the parsing logic yourself; take a look at NSScanner, which would let you read up to a space or double-quote, look at what you get back, and then read to the next space/double-quote, etc.
Example:
#interface ItemParser : NSObject<CHCSVParserDelegate>
- (NSArray *)itemsFromString:(NSString *)input;
#end
#implementation ItemParser {
NSMutableArray *_results;
}
- (NSArray *)itemsFromString:(NSString *)input {
_results = [NSMutableArray array];
NSStringEncoding encoding = [input fastestEncoding];
NSInputStream *stream = [NSInputStream inputStreamWithData:[input dataUsingEncoding:encoding]];
CHCSVParser *parser = [[CHCSVParser alloc] initWithInputStream:stream usedEncoding:&encoding delimiter:' '];
parser.delegate = self;
[parser parse];
return _results;
}
- (void)parser:(CHCSVParser *)parser didReadField:(NSString *)field atIndex:(NSInteger)fieldIndex {
[_results addObject:field];
}
#end
You'd use it like this:
NSString *example = #"100 200 300 \"TEST ITEM\" 500";
ItemParser *parser = [[ItemParser alloc] init];
NSLog(#"%#", [parser itemsFromString:example]);
Here's an NSString category that uses an NSScanner to split a string into search terms, respecting various types of quote pairs: "" '' ‘’ “”
Usage:
NSArray *terms = [#"This is my \"search phrase\" I want to split" searchTerms];
// results in: ["This", "is", "my", "search phrase", "I", "want", "to", "split"]
Code:
#interface NSString (Search)
- (NSArray *)searchTerms;
#end
#implementation NSString (Search)
- (NSArray *)searchTerms {
// Strip whitespace and setup scanner
NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSString *searchString = [self stringByTrimmingCharactersInSet:whitespace];
NSScanner *scanner = [NSScanner scannerWithString:searchString];
[scanner setCharactersToBeSkipped:nil]; // we'll handle whitespace ourselves
// A few types of quote pairs to check
NSDictionary *quotePairs = #{#"\"": #"\"",
#"'": #"'",
#"\u2018": #"\u2019",
#"\u201C": #"\u201D"};
// Scan
NSMutableArray *results = [[NSMutableArray alloc] init];
NSString *substring = nil;
while (scanner.scanLocation < searchString.length) {
// Check for quote at beginning of string
unichar unicharacter = [self characterAtIndex:scanner.scanLocation];
NSString *startQuote = [NSString stringWithFormat:#"%C", unicharacter];
NSString *endQuote = [quotePairs objectForKey:startQuote];
if (endQuote != nil) { // if it's a valid start quote we'll have an end quote
// Scan quoted phrase into substring (skipping start & end quotes)
[scanner scanString:startQuote intoString:nil];
[scanner scanUpToString:endQuote intoString:&substring];
[scanner scanString:endQuote intoString:nil];
} else {
// Single word that is non-quoted
[scanner scanUpToCharactersFromSet:whitespace intoString:&substring];
}
// Process and add the substring to results
if (substring) {
substring = [substring stringByTrimmingCharactersInSet:whitespace];
if (substring.length) [results addObject:substring];
}
// Skip to next word
[scanner scanCharactersFromSet:whitespace intoString:nil];
}
// Return non-mutable array
return results.copy;
}
#end

How to right pad a string using stringWithFormat

I would like to be able to right align a string using spaces. I have to be able to use the stringWithFormat: method.
So far I have tried the recommended format and it does not seem to work: [NSString stringWithFormat:#"%10#",#"test"].
I would expect this to return a string that has six spaces followed by "test" but all I am getting is "test" with no spaces.
It appears that stringWithFormat ignores the sizing requests of the %# format specifier. However, %s specifier works correctly:
NSString *test = #"test";
NSString *str = [NSString stringWithFormat:#"%10s", [test cStringUsingEncoding:NSASCIIStringEncoding]];
NSLog(#"'%#'", str);
This prints ' test'.
It's C style formatting. %nd means the width is n.
check following code.
NSLog(#"%10#",[NSString stringWithFormat:#"%10#",#"test"]);
NSLog(#"%#",[NSString stringWithFormat:#" %#",#"test"]);
NSLog(#"%10#", #"test");
NSLog(#"%10s", [#"test" cStringUsingEncoding:[NSString defaultCStringEncoding]]);
NSLog(#"%10d", 1);
NSString *str = #"test";
int padding = 10-[str length]; //6
if (padding > 0)
{
NSString *pad = [[NSString string] stringByPaddingToLength:padding withString:#" " startingAtIndex:0];
str = [pad stringByAppendingString:str];
}
NSLog(#"%#", str);

Resources