w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
How to convert 0 byte array to string in objective c?
to create and free 0 length array: char *arr = malloc(0); // do something with arr, actually you cant do much with it free(arr); to convert null-terminated c string to NSString: const char *cstr = "test"; NSString *str = @(cstr); // or NSString *str2 = [NSString stringWithUTF8String:cstr]; to convert char array to NSString: char arr[5] = "test"; NSString *str = [[NSString alloc] initWithBytes:arr length:5 encoding:NSUTF8StringEncoding]; you can check NSString doc for more details

Categories : Objective C

Convert a numeric value in a string to integer in Objective C/C
And that's where a forgotten NSNumberFormatter can show what it's capable of doing. After you parsed your input string (using regular expression magic or NSString's componentsSeparatedByString:, I'll not be discussing that step) and obtained the spell-out number, you can use NSNumberFormatter's NSNumberFormatterSpellOutStyle to quickly convert your string into a number: NSString *obtainedDegreesString = @"thirty-two"; NSNumberFormatter *spellOutFormatter = [[NSNumberFormatter alloc] init]; [spellOutFormatter setLocale:[NSLocale currentLocale]]; // or whatever locale you want [spellOutFormatter setNumberStyle:NSNumberFormatterSpellOutStyle]; NSNumber *degreesNumber = [spellOutFormatter numberFromString:obtainedDegreesString]; NSLog(@"%d", degreesNumber.intValue); // logs 32 But warning

Categories : Iphone

Convert Objective-C enum constants to string names
lldb doesn't have any special capabilities regarding printing enum names. I think what you're seeing is the result of the enum values being recorded in the debug info (or not). For instance, enum myenums {a = 0, b, c}; int main () { enum myenums var = b; return (int) var; // break here } % xcrun clang -g a.c % xcrun lldb a.out (lldb) br s -p break Breakpoint 1: where = a.out`main + 18 at a.c:5, address = 0x0000000100000f92 (lldb) r [...] -> 5 return (int) var; // break here 6 } (lldb) p var (myenums) $0 = b (lldb) p (myenums) 0 (myenums) $1 = a (lldb) If you look at the debug info for this binary (dwarfdump a.out.dSYM) you'll see that the variable var's type is myenums and the debug information includes the values of those enumerated types: 0x0000005a: TAG_enum

Categories : Objective C

Objective C: how to convert nested NSDictionarys and NSArrays to URLEncoded string
Holy Cow! I had to dust off some really old PHP knowledge for this: http_build_query(). The format of a complex mixed dictionary/array objects is base[key][key]…[key]=value For the JSON {"key1": "value1", "key2": ["value2", "value3"]}, PHP would expect key1=value1&key2[0]=value3&key2[1]=value3 as a URL encoded string (so key1=value1&key2%5B0%5D=value3&key2%5B1%5D=value3). For a more complex example: {"x": {"y": ["a", "b"]}, "z" : "c"}, PHP would expect x[y][0]=a&x[y][1]=b&z=c.

Categories : Objective C

Objective-C: extract numeric fraction in string and convert it to a real number
This should solve the problem: NSString *input = @"3/4 pounds of sugar"; // trim white space at the beginning and end input = [input stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; // define charater set to split NSCharacterSet *chSet = [NSCharacterSet characterSetWithCharactersInString:@" /"]; // split string into array of strings by charaters '/' and ' ' NSArray *split = [input componentsSeparatedByCharactersInSet:chSet]; // the result of the fraction inside result double result = [split[0] doubleValue] / [split[1] doubleValue];

Categories : Objective C

(Objective-)C++ Duplicate symbol on template specialization
Your error is twofold. First of all you write template code in a .cpp file. Then, to correct that error, you include the .cpp file in a header, another bad idea. Why? A class template is not really a class, yet, just a template for a group of classes. The classes that can be made from it are created as needed. A .cpp file, on the other hand, is only compiled once, which is not enough and not even meaningful, since you only have a template at this point. On the other hand, to include a .cpp file is a bad thing in itself, since it typically results in recompilation of code that may not be recompiled, hence the link errors. EDIT: Either you can define the specializations in a .cpp file (but no pure template code, and don't include it!), or you can inline them and keep them in the header:

Categories : C++

Constants in Objective-C and "duplicate symbol" linker error
If you want to use constant only in one .m file then declare it as static. For example:static NSString * const CONSTANT_STRING = @"Constant I am". In case of NSInteger you can write in your every .m file: static const NSInteger my_const = 3; If you want globals (one constant with one value visible in every file) then write in your .h: extern const NSInteger my_global_const; and in your .m file you can add const NSInteger my_global_const = 5;

Categories : IOS

How can I convert a query string into a a shorter alphanumeric string (and convert it back again) in PHP?
You can use base64_encode() and base64_decode(), but if you want it as a filename, you'll likely hit filename length limit of filesystem (255 chars for ext3). If it's possible you hit this limit, you can use each X chars as directory name, and create full path.

Categories : PHP

error C2664 cannot convert parameter 1 from 'std::string (__thiscall ClassName::* )(std::string)' to 'std::string (__cdecl *)(std::string)
In your real use-case can you simply make FunctionToBePointed a static method? static std::string Class1::FunctionToBePointed(std::string msg) { return msg; } If yes your code should work. The reason is that instance methods are implicitly called with an hidden this pointer, this is the thiscall calling convention, whereas static methods simply use the cdecl convention because they don't work on any instance. EDIT: A sample with Boost::bind: The MyClass C# class: using System; using System.ComponentModel; public class MyClass : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged = delegate{}; private string name; public string Name { get { return name; } set { if (name

Categories : Visual C++

Objective-C: "format string is not a string literal (potentially insecure)" warning with macro
The Clang & GCC compilers check that format strings and the supplied arguments conform, they cannot do this if the format string is not a literal - hence the error message you see as you are obtaining the format string from the bundle. To address this issue there is an attribute, format_arg(n) (docs), to mark functions which take a format string; alter it in some way without changing the actual format specifiers, e.g translate it; and then return it. Cocoa provides the convenient macro NS_FORMAT_ARG(n) for this attribute. To fix your problem you need to do two things: Wrap up the call to NSBundle in a function with this attribute specified; and Change your "key" to include the format specifiers. Second first, your strings file should contain: "name %@" = "My name is %@" so the

Categories : IOS

i'm trying to get a grip on how to convert an interface from android to objective-c
If you declare something need to be used by other classes you can declare them in .h. But if you need specifically for that class declare it in .m If you would like var's and data of another . It should be declare in .h

Categories : Java

how do i convert Dictionary string string to array of key value pair of string and string using linq and c#
try below , you may need to change the set properties of new object accordingly ArrayOfKeyValueOfstringstringKeyValueOfstringstring[] array = valuePairs.Select(pair => new ArrayOfKeyValueOfstringstringKeyValueOfstringstring(){ Key= pair.Key, Value= pair.Value}).ToArray();

Categories : C#

Best way to convert Back and forth from Unichars to display characters? Objective C
This should work for you: NSString *text = inputView.text; // For example "u267B" NSLog(@"%@", text); // Output: u267B NSData *d = [text dataUsingEncoding:NSASCIIStringEncoding]; NSString *converted = [[NSString alloc] initWithData:d encoding:NSNonLossyASCIIStringEncoding]; NSLog (@"%@", converted); // Output: ♻ outputView.text = converted; It uses the fact that NSNonLossyASCIIStringEncoding decodes uNNNN to the corresponding Unicode character. To convert in the other direction (from "♻" to "u267B"), you just have to exchange NSASCIIStringEncoding and NSNonLossyASCIIStringEncoding in the above code. UPDATE: As you correctly noticed, the "reverse direction" does not encode characters in the range <= U+00FF. The following code converts these characters as well: NSString *text =

Categories : Objective C

Are there languages which compile to Objective-C or are binary compatible with Objective-C -> Coffeescript for Objective-C
While the primary way to use eero is to have it compile to native code, it does support source-to-source translation as well (from eero to standard Objective-C/C++). Please see https://github.com/eerolanguage/eero/wiki/Translator for more details. It really needs to be documented in a more obvious place...

Categories : IOS

Find an 8 digit string within a string - Objective C
NSString *yourString = @"ALLee;YIeiqm Y E JOHNSON-TEST g jammima g 02345678 8;;Y_(____. g GHJ- 444 4333333333 * BAKERY -- Scones p ii"; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[A-Za-z0-9]{8}" options:NSRegularExpressionCaseInsensitive error:&error]; [regex enumerateMatchesInString:yourString options:0 range:NSMakeRange(0, [yourString length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){ // your code to handle matches here }]; (code shamelessly nicked from this SO answer).

Categories : IOS

Convert to string, remove some parts and convert back to byte[]
What you are looking for is Encoding.GetString not Base64 string. var newstr = String.Join(Environment.NewLine, Encoding.UTF8.GetString(buf) .Split(new char[] { ' ', ' ' }) .Skip(4)); buf = Encoding.UTF8.GetBytes(newstr);

Categories : C#

convert a hexadecimal into a decimal via string convert in java
Use the overloaded Integer.parseInt method that takes a second parameter for the radix: Integer.parseInt(str1, 16);

Categories : Java

java.lang.IllegalArgumentException: duplicate key: class javax.faces.convert.DoubleConverter
The webapp's runtime classpath covers more than only /WEB-INF/lib. It also covers among others server's own /lib folder and, if any, the "common" and "shared" libraries which are server-specific and configurable in server end. It also covers the JRE's /lib and /lib/ext folder. Usually, those folders are not to be touched by developers, for sure not by starters. Apparently you've somehow a copy of RichFaces JAR in one of those places. At least, the fact that you keep getting this exception while having a proper /WEB-INF/lib confirms this. To figure the exact local disk file system paths covered by the runtime classpath, run just for debug this piece of code in your webapp, e.g. in constructor of a test backing bean: System.out.println("The current runtime classpath covers the following p

Categories : JSF

Objective C why format string as string
The argument that is passed in could be any subclass of string, including NSMutableString. This code creates an immutable copy of it. This means that you can store the returned string without having to worry about someone else modifying it. A better way of doing this would be: NSString *string2 = [string copy]; According to the NSCopying Protocol reference: The copy returned is immutable if the consideration “immutable vs. mutable” applies to the receiving object.

Categories : IOS

Convert Colon Separated String to a Dictionary
string s = "Number1.pdf:Alpha1.pdf; Number2.pdf:Alpha2.pdf; Number3.pdf:Alpha3.pdf;"; var names = s.Replace(".pdf","") .Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries) .Select(x => x.Split(':')) .ToDictionary(x => x[0].Trim(), x => x[1]);

Categories : C#

Objective C / Get string from URL
For iOS 7+ and OS X 10.9+ use: NSURLSession *aSession = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; [[aSession dataTaskWithURL:[NSURL URLWithString:@"http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (((NSHTTPURLResponse *)response).statusCode == 200) { if (data) { NSString *contentOfURL = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@", contentOfURL); } } }] resume]; For earlier versions use: [NSURLConnection sendAsynchronousRequest:[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml"]] queue:[NSOperationQueue

Categories : Objective C

Concise string slicing in objective C
Try substringWithRange:. For instance [s substringWithRange:NSMakeRange(1, s.length - 1)] or [s substringWithRange:NSMakeRange(1, 4 - 1)]

Categories : Python

Writing string to a file in Objective C
Another option is using NSString's writeToFile:atomically:encoding:error: method: put your string objects into an NSArray, make a string out of them, and write the whole thing to a file: NSString *firstString = @"Quick brown fox jumps over the lazy dog"; NSString *secondString = @"Jackdaws love my big sphinx of quartz"; NSArray *myStrings = @[firstString, secondString]; NSString *bigString = [myStrings componentsJoinedByString:@" "]; NSError *error = null; [bigString writeToFile:@"filename" atomically:NO encoding:NSUTF8StringEncoding error:&error];

Categories : IOS

Replacing a regex with a string in Objective C?
You can use the following code for doing this: NSString *yourString = @"123, 456,789, 012"; NSError *err = NULL; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@", {0,}" options:NSRegularExpressionCaseInsensitive error:&err]; NSString *modifiedString = [regex stringByReplacingMatchesInString:yourString options:0 range:NSMakeRange(0, [yourString length]) withTemplate:@", "]; NSLog(@"%@", modifiedString);

Categories : IOS

Check if string is palindrome in objective c
Apart from the unbalanced braces, accessing a character from NSString is more complicated than using array notation. You need to use the method characterAtIndex: You can optimise your code, by breaking out of the loop if a palindrome is impossible and taking the length call outside of the for loop. NSString *p = @"121"; NSInteger length = p.length; NSInteger halfLength = (length / 2); BOOL isPalindrome = YES; for (int i = 0; i < halfLength; i++) { if ([p characterAtIndex:i] != [p characterAtIndex:length - i - 1]) { isPalindrome = NO; break; } } It may be desirable to check case insensitively. To do this, make the string be all lowercase before looping, using the lowercaseString method. As pointed out by Nikolai in the comments, this would only work for s

Categories : Objective C

Obfuscating a number(in a string) Objective C
The problem is your last line. You create the new string with the original, unmodified data object. You need to create a new NSData object from the modified dataPtr bytes. NSData *newData = [NSData dataWithBytes:dataPtr length:data.length]; return [[NSString alloc] initWithData:newData encoding:NSUTF8StringEncoding]; But you have some bigger issues. The calls to bytes returns a constant, read-only reference to the bytes in the NSData object. You should NOT be modifying that data. The result of your XOR on the character data could, in theory, result in a byte stream that is no longer a valid UTF-8 encoded string.

Categories : IOS

Get duplicate characters in string
Well, I think falsetru had a good idea with a zero-width look-ahead. 'abcabc123123'.match(/(.+)(?=1)/g) // ["abc", "123"] This allows it to match just the initial substring while ensuring at least 1 repetition follows. For M42's follow-up example, it could be modified with a .*? to allow for gaps between repetitions. 'abc123ab12'.match(/(.+)(?=.*?1)/g) // ["ab", "12"] Then, to find where the repetition starts with multiple uses together, a quantifier ({n}) can be added for the capture group: 'abcabc1234abc'.match(/(.+){2}(?=.*?1)/g) // ["abcabc"] Or, to match just the initial with a number of repetitions following, add the quantifier within the look-ahead. 'abc123ab12ab'.match(/(.+)(?=(.*?1){2})/g) // ["ab"] It can also match a minimum number of repetitions with a range quanti

Categories : Javascript

Objective-C: Randomly replace characters in string
If the number of characters to remove/replace is small compared to the length of the string, then your solution is good, because the probability of a "collision" in the while-loop is small. You can improve the method by using a single mutable string instead of allocating a new string in each step: NSString *string = @"Remove Some Characters"; int totalRemove = 5; NSMutableString *result = [string mutableCopy]; for (int j=0; j < totalRemove; j++) { int replaceLocation; do { replaceLocation = arc4random_uniform((int)[result length]); } while ([result characterAtIndex:replaceLocation] == '_' || [result characterAtIndex:replaceLocation] == ' '); [result replaceCharactersInRange:NSMakeRange(replaceLocation, 1) withString:@"_"]; } If the number of characters to r

Categories : Objective C

Objective C Array Count String Issue
"componentsSeparatedByString" returns an NSArray object, not a single NSString. An array object can contain zero, one or more NSString objects, depending on the input. If you change "FinishWholeQuestion" into a NSArray object, you'll likely get a few components (separate by a string). And now that I'm looking at your code a little more closely, I see you're making an assumption that your array is always valid (and has more than 2 entries, as evidenced by the "objectAtIndex: 1" bit). You should also change the first character of all your Objective-C variables. Best practices in Objective-C are that the first character of variables should always be lower case. Like this: NSString * getUrl = [NSString stringWithFormat:@"http://www.mywebpage.com/page.php"]; NSString * getAllHtml = [NS

Categories : IOS

How to make a binary to string converter in Objective-C
Here you go NSString *str = @"01100010 01110010 01101001 01100001 01101110 00110001 00110010 00110011"; NSString *str2 = stringFromBinString(str); NSLog(@"%@",str2); // brian123 This is the function that can convert // Function that converts NSString* stringFromBinString(NSString* binString) { NSArray *tokens = [binString componentsSeparatedByString:@" "]; char *chars = malloc(sizeof(char) * ([tokens count] + 1)); for (int i = 0; i < [tokens count]; i++) { const char *token_c = [[tokens objectAtIndex:i] cStringUsingEncoding:NSUTF8StringEncoding]; char val = (char)strtol(token_c, NULL, 2); chars[i] = val; } chars[[tokens count]] = 0; NSString *result = [NSString stringWithCString:chars encoding

Categories : Objective C

Objective-C append to string not working NSXMLParser
The stringByAppendingString function returns a NSString. It doesn't alter the receiver. You need to fix your use of stringByAppendingString. For example, in foundCharacters, replace this: [arrayString stringByAppendingString:string]; With this: arrayString = [arrayString stringByAppendingString:string]; Apple's documentation on stringByAppendingString: stringByAppendingString: Returns a new string made by appending a given string to the receiver. Also, when appending strings, don't forget to initialize the string before you append to it.

Categories : IOS

Obtaining the string value from separate window to be used on another. Objective C
It's not super intuitive to figure out from Apple's documentation, but to get the raw string value of a NSTextView (which inherits from NSText), just use: [_txtTextView string]; And since you're using properties, it might be smarter to use the accessor in your function, like this: - (NSString*)getText{ return [self.txtTextView string]; }

Categories : Objective C

Check if a string is an objective c method declaration
To do this correctly/precisely is hard. While a method declaration doesn't look too complicated as it potentially contains any type declaration possible in C - and a common quiz question is "What does this C declaration mean?" - the syntax is actually quite involved. Compound that with, to my knowledge, there being no published BNF for Objective-C (though you might find one in the Clang source), and you've got a challenge on your hands. So you do need to write your own parser, but you can probably tackle it in a fuzzy/imprecise way - assume the input is valid and "tokenise" it fuzzily based, say, not on what you expect but on what you don't expect - so an argument type is not a C type declaration but just an parenthesised string which might contain other balanced parentheses, and you can

Categories : Objective C

Objective C - Multi line string using stringByAppendingFormat
assign empty string to multiLineTitle or allocate memory for multiLineTitle. NSString *multiLineTitle = @""; or NSString *multiLineTitle = [[NSString alloc]init];

Categories : Objective C

Objective-C inheritance, string propagation to superclass
m_name is an NSString, not a char *. You have to log it using the %@ format specifier instead of %s. Read the documentation for format strings. Comments: Objective-C is not C++. Don't try to enforce C++ style naming conventions. Call that instance variable name, or animalName, or theName or whatever. Don't call it m_name. The initializers are conventionally called initWithWhatever:, not initWhatever:. It reflects better the purpose of the method (you init the object with the name, and not the name itself). Do check the return value of [super init]. If it returns nil, your initializer will crash. An idiomatic solution is if (self = [super initWithName:name]) The initializer methods, again conventionally, return id.

Categories : Objective C

How to convert a string with hexadecimal characters in a string to a full unicode in Python 2.7
You're reading the bytes from the file. Use codecs.open() to open the file with a given encoding (e.g. UTF-8) so that you read text instead. Also, read this.

Categories : Python

Efficiently convert Java string into null-terminated byte[] representing a C string? (ASCII)
You can use str.getBytes("ISO-8859-1") with a little trick at the end: byte[] stringBytes=str.getBytes("ISO-8859-1"); byte[] ntBytes=new byte[stringBytes.length+1]; System.arrayCopy(stringBytes, 0, ntBytes, 0, stringBytes.length); arrayCopy is relatively fast as it can use native tricks and optimizations in many cases. The new array is filled with null bytes everywhere we didn't overwrite it(basically just the last byte). ntBytes is the array you need.

Categories : Java

Duplicate string names in strings.xml
We just ran into a similar problem today. When one of our devs tried to build a project for the first time the build failed, citing duplicate nodes in strings.xml. Indeed there were duplicates in strings.xml, but this has not been a problem before and everyone else could build the same project with the same strings.xml without a problem. In our case, the solution was found in the 'Project Structure' settings of the intellij project. Our project references some other 'Android Library' projects but the Developer that couldn't build didn't have the 'library project' checkbox ticked in the relevant module's 'Android' configuration node. Once this checkbox was ticked the project built successfully, and we confirmed that unchecking the box would make the compile fail. I can't say why this o

Categories : Android

deleting a duplicate character in a string
You can use a do...while loop until you get a unique character. Also using String.indexOf will tell you about duplicates: var WordToGuess = "MYWORD"; do { var char = GetRandomCharacter(); } while ( WordToGuess.indexOf(char) > -1 ); WordToGuess += char; function GetRandomCharacter() { var wordsTable = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']; var Hiddenletter = wordsTable[Math.floor((Math.random() * 26) + 1)]; return Hiddenletter; } Actually one of the places do...while goes better than a regular while.

Categories : Javascript

How to delete duplicate lines from string?
var pieces = s.split(" "); //This will split your string var output = []; //Output array for (var i = 0; i < pieces.length; i++) { //Iterate over input... if (pieces[i] == '<BR>' || output.indexOf(pieces[i]) < 0) { //If it is <BR> or not in output, add to output output.push(pieces[i]); } } var newS = output.join(" "); //Concatenates the string back, you don't have to do this if you want your lines in the array Here we have the jsFiddle: http://jsfiddle.net/7s88t/ For you knowledge, the indexOf function returns the position where pieces[i] is at output array. If it is not found, it returns -1. That is why I check if it is less than zero. Hope I have helped. EDIT As you requested, to take lower case: if (pieces[i].toLowerCase() == '<br>' || piec

Categories : Javascript



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.