How do I check if a C++ std::string starts with a certain string, and convert a substring to an int?

How do I implement the following (Python pseudocode) in C++? if argv[1].startswith(‘–foo=’): foo_value = int(argv[1][len(‘–foo=’):]) (For example, if argv[1] is –foo=98, then foo_value is 98.) Update: I’m hesitant to look into Boost, since I’m just looking at making a very small change to a simple little command-line tool (I’d rather not have to learn how … Read more

How to trim a file extension from a String in JavaScript?

For example, assuming that x = filename.jpg, I want to get filename, where filename could be any file name (Let’s assume the file name only contains [a-zA-Z0-9-_] to simplify.). I saw x.substring(0, x.indexOf(‘.jpg’)) on DZone Snippets, but wouldn’t x.substring(0, x.length-4) perform better? Because, length is a property and doesn’t do character checking whereas indexOf() is … Read more

How does String substring work in Swift

I’ve been updating some of my old code and answers with Swift 3 but when I got to Swift Strings and Indexing with substrings things got confusing. Specifically I was trying the following: let str = “Hello, playground” let prefixRange = str.startIndex..<str.startIndex.advancedBy(5) let prefix = str.substringWithRange(prefixRange) where the second line was giving me the following … Read more

If strings are immutable in .NET, then why does Substring take O(n) time?

Given that strings are immutable in .NET, I’m wondering why they have been designed such that string.Substring() takes O(substring.Length) time, instead of O(1)? i.e. what were the tradeoffs, if any? 5 Answers 5 UPDATE: I liked this question so much, I just blogged it. See Strings, immutability and persistence The short answer is: O(n) is … Read more

How do I check if a string contains another string in Swift?

In Objective-C the code to check for a substring in an NSString is: NSString *string = @”hello Swift”; NSRange textRange =[string rangeOfString:@”Swift”]; if(textRange.location != NSNotFound) { NSLog(@”exists”); } But how do I do this in Swift? 28 s 28 You can do exactly the same call with Swift: Swift 4 & Swift 5 In Swift … Read more

What is the difference between substr and substring?

What is the difference between alert(“abc”.substr(0,2)); and alert(“abc”.substring(0,2)); They both seem to output “ab”. 1Best Answer 11 The difference is in the second argument. The second argument to substring is the index to stop at (but not include), but the second argument to substr is the maximum length to return. Links? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring