Search Results

Search found 35302 results on 1413 pages for 'string literals'.

Page 8/1413 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • NameValueCollection vs Dictionary<string,string>

    - by frankadelic
    Any reason I should use Dictionary<string,string instead of NameValueCollection? (in C# / .NET Framework) Option 1, using NameValueCollection: //enter values: NameValueCollection nvc = new NameValueCollection() { {"key1", "value1"}, {"key2", "value2"}, {"key3", "value3"} }; // retrieve values: foreach(string key in nvc.AllKeys) { string value = nvc[key]; // do something } Option 2, using Dictionary<string,string... //enter values: Dictionary<string, string> dict = new Dictionary<string, string>() { {"key1", "value1"}, {"key2", "value2"}, {"key3", "value3"} }; // retrieve values: foreach (KeyValuePair<string, string> kvp in dict) { string key = kvp.Key; string val = kvp.Value; // do something } For these use cases, is there any advantage to use one versus the other? Any difference in performance, memory use, sort order, etc.?

    Read the article

  • How to have a function with a nullable string parameter in Go?

    - by yuku
    I'm used to Java's String where we can pass null rather than "" for special meanings, such as use a default value. In Go, string is a primitive type, so I cannot pass nil (null) to a parameter that requires a string. I could write the function using pointer type, like this: func f(s *string) so caller can call that function either as f(nil) or // not so elegant temp := "hello"; f(&temp) but the following is unfortunately not allowed: // elegant but disallowed f(&"hello"); What is the best way to have a parameter that receives either a string or nil?

    Read the article

  • handle null values for string when implementing IXmlSerializable interface

    - by user208081
    I have the following class that implements IXmlSerializable. When implementing WriteXml(), I need to handle the case where the string members of this class may be null values. What is the best way of handling this? Currently, I am using the default constructor in which all the string properties are initialized to empty string values. This way, when WriteXml() is called, the string will not be null. One other way I could do this is check using String.IsNullOrEmpty before writing each string in xml. Any suggestions on how I can improve this code? using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Serialization; using System.Globalization; namespace TCS.Common.InformationObjects { public sealed class FaxSender : IXmlSerializable { #region Public Constants private const string DEFAULT_CLASS_NAME = "FaxSender"; #endregion Public Constants #region Public Properties public string Name { get; set; } public string Organization { get; set; } public string PhoneNumber { get; set; } public string FaxNumber { get; set; } public string EmailAddress { get; set; } #endregion Public Properties #region Public Methods #region Constructors public FaxSender() { Name = String.Empty; Organization = String.Empty; PhoneNumber = String.Empty; FaxNumber = String.Empty; EmailAddress = String.Empty; } public FaxSender(string name, string organization, string phoneNumber, string faxNumber, string emailAddress) { Name = name; Organization = organization; PhoneNumber = phoneNumber; FaxNumber = faxNumber; EmailAddress = emailAddress; } #endregion Constructors #region IXmlSerializable Members public System.Xml.Schema.XmlSchema GetSchema() { throw new NotImplementedException(); } public void ReadXml(System.Xml.XmlReader reader) { throw new NotImplementedException(); } public void WriteXml(System.Xml.XmlWriter xmlWriter) { try { // <sender> xmlWriter.WriteStartElement("sender"); // Write the name of the sender as an element. xmlWriter.WriteElementString("name", this.Name.ToString(CultureInfo.CurrentCulture)); // Write the organization of the sender as an element. xmlWriter.WriteElementString("organization", this.Organization.ToString(CultureInfo.CurrentCulture)); // Write the phone number of the sender as an element. xmlWriter.WriteElementString("phone_number", this.PhoneNumber.ToString(CultureInfo.CurrentCulture)); // Write the fax number of the sender as an element. xmlWriter.WriteElementString("fax_number", this.FaxNumber.ToString(CultureInfo.CurrentCulture)); // Write the email address of the sender as an element. xmlWriter.WriteElementString("email_address", this.EmailAddress.ToString(CultureInfo.CurrentCulture)); // </sender> xmlWriter.WriteEndElement(); } catch { // Rethrow any exceptions. throw; } } #endregion IXmlSerializable Members #endregion Public Methods } }

    Read the article

  • Determining Whether a String Is Contained Within a String Array (Case Insensitive)

    About once every couple of months I need to write a bit of code that does one thing if a particular string is found within an array of strings and something else if it is not ignoring differences in case. For whatever reason, I never seem to remember the code snippet to accomplish this, so after spending 10 minutes of research today I thought I'd write it down here in an effort to help commit it to memory or, at the very least, serve as a quick place to find the answer when the need arises again.So without further adieu, here it is:Visual Basic Version:If stringArrayName.Contains("valueToLookFor", StringComparer.OrdinalIgnoreCase) Then ... Else ... End IfC# Version:if (stringArrayName.Contains("valueToLookFor", StringComparer.OrdinalIgnoreCase)) ... else ...Without the StringComparer.OrdinalIgnoreCase the search will be case-sensitive. For more information on comparing strings, see: New Recommendations for Using Strings in Microsoft .NET 2.0.Happy Programming!Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • Editing XML Literals Embedded Expressions in Visual Basic 2010 (Avner Aharoni)

    The implicit line continuation feature in Visual Basic 2010 provided an opportunity to improve the code editing experience in XML literals embedded expressions. In Visual Studio 2008, pressing Enter inside an embedded expression would result in the cursor being positioned to the left of the end embedded expression tag. In Visual Studio 2010, pressing Enter inserts a newline for the cursor, and the end embedded expression tag moves to the line below. This minimizes the number of key strokes needed...Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • How can variadic char template arguments from user defined literals be converted back into numeric types?

    - by Pubby
    This question is being asked because of this one. C++11 allows you to define literals like this for numeric literals: template<char...> OutputType operator "" _suffix(); Which means that 503_suffix would become <'5','0','3'> This is nice, although it isn't very useful in the form it's in. How can I transform this back into a numeric type? This would turn <'5','0','3'> into a constexpr 503. Additionally, it must also work on floating point literals. <'5','.','3> would turn into int 5 or float 5.3 A partial solution was found in the previous question, but it doesn't work on non-integers: template <typename t> constexpr t pow(t base, int exp) { return (exp > 0) ? base * pow(base, exp-1) : 1; }; template <char...> struct literal; template <> struct literal<> { static const unsigned int to_int = 0; }; template <char c, char ...cv> struct literal<c, cv...> { static const unsigned int to_int = (c - '0') * pow(10, sizeof...(cv)) + literal<cv...>::to_int; }; // use: literal<...>::to_int // literal<'1','.','5'>::to_int doesn't work // literal<'1','.','5'>::to_float not implemented

    Read the article

  • How Do I Remove The First 4 Characters From A String If It Matches A Pattern In Ruby

    - by James
    I have the following string: "h3. My Title Goes Here" I basically want to remove the first 4 characters from the string so that I just get back: "My Title Goes Here". The thing is I am iterating over an array of strings and not all have the h3. part in front so I can't just ditch the first 4 characters blindly. I have checked the docs and the closest think I could find was chomp, but that only works for the end of a string. Right now I am doing this: "h3. My Title Goes Here".reverse.chomp(" .3h").reverse This gives me my desired output, but there has to be a better way right? I mean I don't want to reverse a string twice for no reason. I am new to programming so I might have missed something obvious, but I didn't see the opposite of chomp anywhere in the docs. Is there another method that will work? Thanks!

    Read the article

  • How to find first non-repetitive character from a string?

    - by masato-san
    I've spent half day trying to figure out this and finally I got working solution. However, I feel like this can be done in simpler way. I think this code is not really readable. Problem: Find first non-repetitive character from a string. $string = "abbcabz" In this case, the function should output "c". The reason I use concatenation instead of $input[index_to_remove] = '' in order to remove character from a given string is because if I do that, it actually just leave empty cell so that my return value $input[0] does not not return the character I want to return. For instance, $str = "abc"; $str[0] = ''; echo $str; This will output "bc" But actually if I test, var_dump($str); it will give me: string(3) "bc" Here is my intention: Given: input while first char exists in substring of input { get index_to_remove input = chars left of index_to_remove . chars right of index_to_remove if dupe of first char is not found from substring remove first char from input } return first char of input Code: function find_first_non_repetitive2($input) { while(strpos(substr($input, 1), $input[0]) !== false) { $index_to_remove = strpos(substr($input,1), $input[0]) + 1; $input = substr($input, 0, $index_to_remove) . substr($input, $index_to_remove + 1); if(strpos(substr($input, 1), $input[0]) == false) { $input = substr($input, 1); } } return $input[0]; }

    Read the article

  • Querying Literals in Entity SQL

    Entity SQL might surprise you if you are building query expressions with some non-string types. Ive blogged about this before with the DateTime literal after trying to use a string to represent the date in my query as Im used to with TSQL. Here is a snip from that post: SELECT VALUE BAModel.Contact(c.ContactID,c.FirstName,c.LastName,c.Title,c.AddDate,c.ModifiedDate) FROM dbo.Contact as c WHERE c.AddDate>="1/1/2007" I was trying to emulate T-SQL here but I need...Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • JavaScript: Given an offset and substring length in an HTML string, what is the parent node?

    - by Bungle
    My current project requires locating an array of strings within an element's text content, then wrapping those matching strings in <a> elements using JavaScript (requirements simplified here for clarity). I need to avoid jQuery if at all possible - at least including the full library. For example, given this block of HTML: <div> <p>This is a paragraph of text used as an example in this Stack Overflow question.</p> </div> and this array of strings to match: ['paragraph', 'example'] I would need to arrive at this: <div> <p>This is a <a href="http://www.example.com/">paragraph</a> of text used as an <a href="http://www.example.com/">example</a> in this Stack Overflow question.</p> </div> I've arrived at a solution to this by using the innerHTML() method and some string manipulation - basically using the offsets (via indexOf()) and lengths of the strings in the array to break the HTML string apart at the appropriate character offsets and insert <a href="http://www.example.com/"> and </a> tags where needed. However, an additional requirement has me stumped. I'm not allowed to wrap any matched strings in <a> elements if they're already in one, or if they're a descendant of a heading element (<h1> to <h6>). So, given the same array of strings above and this block of HTML (the term matching has to be case-insensitive, by the way): <div> <h1>Example</a> <p>This is a <a href="http://www.example.com/">paragraph of text</a> used as an example in this Stack Overflow question.</p> </div> I would need to disregard both the occurrence of "Example" in the <h1> element, and the "paragraph" in <a href="http://www.example.com/">paragraph of text</a>. This suggests to me that I have to determine which node each matched string is in, and then traverse its ancestors until I hit <body>, checking to see if I encounter a <a> or <h_> node along the way. Firstly, does this sound reasonable? Is there a simpler or more obvious approach that I've failed to consider? It doesn't seem like regular expressions or another string-based comparison to find bounding tags would be robust - I'm thinking of issues like self-closing elements, irregularly nested tags, etc. There's also this... Secondly, is this possible, and if so, how would I approach it?

    Read the article

  • Parsing string logic issue c#

    - by N0xus
    This is a follow on from this question My program is taking in a string that is comprised of two parts: a distance value and an id number respectively. I've split these up and stored them in local variables inside my program. All of the id numbers are stored in a dictionary and are used check the incoming distance value. Though I should note that each string that gets sent into my program from the device is passed along on a single string. The next time my program receives that a signal from a device, it overrides the previous data that was there before. Should the id key coming into my program match one inside my dictionary, then a variable held next to my dictionaries key, should be updated. However, when I run my program, I don't get 6 different values, I only get the same value and they all update at the same time. This is all the code I have written trying to do this: Dictionary<string, string> myDictonary = new Dictionary<string, string>(); string Value1 = ""; string Value2 = ""; string Value3 = ""; string Value4 = ""; string Value5 = ""; string Value6 = ""; void Start() { myDictonary.Add("11111111", Value1); myDictonary.Add("22222222", Value2); myDictonary.Add("33333333", Value3); myDictonary.Add("44444444", Value4); myDictonary.Add("55555555", Value5); myDictonary.Add("66666666", Value6); } private void AppendString(string message) { testMessage = message; string[] messages = message.Split(','); foreach(string w in messages) { if(!message.StartsWith(" ")) outputContent.text += w + "\n"; } messageCount = "RSSI number " + messages[0]; uuidString = "UUID number " + messages[1]; if(myDictonary.ContainsKey(messages[1])) { Value1 = messageCount; Value2 = messageCount; Value3 = messageCount; Value4 = messageCount; Value5 = messageCount; Value6 = messageCount; } } How can I get it so that when programs recives the first key, for example 1111111, it only updates Value1? The information that comes through can be dynamic, so I'd like to avoid harding as much information as I possibly can.

    Read the article

  • Fast string suffix checking in C# (.NET 4.0)?

    - by ilitirit
    What is the fastest method of checking string suffixes in C#? I need to check each string in a large list (anywhere from 5000 to 100000 items) for a particular term. The term is guaranteed never to be embedded within the string. In other words, if the string contains the term, it will be at the end of the string. The string is also guaranteed to be longer than the suffix. Cultural information is not important. These are how different methods performed against 100000 strings (half of them have the suffix): 1. Substring Comparison - 13.60ms 2. String.Contains - 22.33ms 3. CompareInfo.IsSuffix - 24.60ms 4. String.EndsWith - 29.08ms 5. String.LastIndexOf - 30.68ms These are average times. [Edit] Forgot to mention that the strings also get put into separate lists, but this is not important. It does add to the running time though. On my system substring comparison (extracting the end of the string using the String.Substring method and comparing it to the suffix term) is consistently the fastest when tested against 100000 strings. The problem with using substring comparison though is that Garbage Collection can slow it down considerably (more than the other methods) because String.Substring creates new strings. The effect is not as bad in .NET 4.0 as it was in 3.5 and below, but it is still noticeable. In my tests, String.Substring performed consistently slower on sets of 12000-13000 strings. This will obviously differ between systems and implementations. [EDIT] Benchmark code: http://pastebin.com/smEtYNYN

    Read the article

  • Advice on String Similarity Metrics (Java). Distance, sounds like or combo?

    - by andreas
    Hello, A part of a process requires to apply String Similarity Algorithms. The results of this process will be stored and produce lets say SS_Dataset. Based on this Dataset, further decisions will have to be made. My questions are: Should i apply one or more string similarity algorithms to produce SS_Dataset ? Any comparisons between algorithms that calculate the 'distance' and the 'Sounds Like' similarity ? Does one family of algorithms produces more accurate results over the other? Does a combination give more accurate results on similarity? Can you recommend implementations that you have worked with? My implementation will include packages from the following libraries http://www.dcs.shef.ac.uk/~sam/simmetrics.html http://jtmt.sourceforge.net/ Regards,

    Read the article

  • Delphi Unicode String Type Stored Directly at its Address

    - by Andreas Rejbrand
    I want a string type that is Unicode and that stores the string directly at the adress of the variable, as is the case of the (Ansi-only) ShortString type. I mean, if I declare a S: ShortString and let S := 'My String', then, at @S, I will find the length of the string (as one byte, so the string cannot contain more than 255 characters) followed by the ANSI-encoded string itself. What I would like is a Unicode variant of this. That is, I want a string type such that, at @S, I will find a unsigned 32-bit integer containing the length of the string in bytes (or in characters, which is half the number of bytes) followed by the Unicode representation of the string. I have tried WideString, UnicodeString, and RawByteString, but they all appear only to store an adress at @S, and the actual string somewhere else (I guess this has do do with reference counting and such). I suspect that there is no built-in type to use, and that I have to come up with my own way of storing text the way I want (which actually is fun). Am I right?

    Read the article

  • Insert string between two markers

    - by user275074
    I have a requirement to insert a string between two markers. Initially I get a sting (from a file stored on the server) between #DATA# and #END# using: function getStringBetweenStrings($string,$start,$end){ $startsAt=strpos($string,$start)+strlen($start); $endsAt=strpos($string,$end, $startsAt); return substr($string,$startsAt,$endsAt-$startsAt); } I do some processing and based on the details of the string, query for some records. If there are records I need to be able to append them at the end of the string and then re-insert the string between #DATA# and #END# within the file on the server. How can I best achieve this? Is it possible to insert a record at a time in the file before #END# or is it best to manipulate the string on the server and just re-insert over the existing string in the file on the server?

    Read the article

  • how to retrieve part of a string in java?

    - by mithun1538
    Hello everyone, I am designing a chat applet. In this, a user will append his name to the beginning of the message that he sends to the other user. In the window of other user, I want to retrieve the appended user name from that string. How do I do that? The message sent by the user is as follows : final_msg = user_name + ": " + user_message Hence I want to know how to retrieve the user_name string only. Is there a function that can retrieve a substring upto the first ":"? I dont want to use final_msg.split(":"), because there is a possiblity that the user_message contains ":", which will then give me an array of strings.

    Read the article

  • Can't return a String value and append it...why?

    - by squeezemylime
    I am writing an app and am having problems returning a simple string value, and I'm not sure why. The function I am using (within a file called APIManager.m) is: - (NSString*) returnVenueUrl { NSString *venueUrl = [devEnvironment stringByAppendingString:@"venue/id/"]; return venueUrl; } I can return this properly by doing this in another .m file: APIManager *apiManager = [APIManager apiManager]; NSLog(@"view venue URL is here: %@", [apiManager returnVenueUrl]); But when I go to append a variable cast as a String onto it, I get nothing.. venueURL = [apiManager returnVenueUrl]; venueURL = [venueURL stringByAppendingString:venueId]; NSLog(@"the Full Venue URL is: %", venueURL); If anyone has any advice on how to fix this, it would be much appreciated!

    Read the article

  • String literal recognition problem

    - by helicera
    Hello! I'm trying to recognize string literal by reading string per symbol. Here is a sample code: #region [String Literal (")] case '"': // {string literal ""} { // skipping '"' ChCurrent = Line.ElementAtOrDefault<Char>(++ChPosition); while(ChCurrent != '"') { Value.Append(ChCurrent); ChCurrent = Line.ElementAtOrDefault<Char>(++ChPosition); if(ChCurrent == '"') { // "" sequence only acceptable if(Line.ElementAtOrDefault<Char>(ChPosition + 1) == '"') { Value.Append(ChCurrent); // skip 2nd double quote ChPosition++; // move position next ChCurrent = Line.ElementAtOrDefault<Char>(++ChPosition); } } else if(default(Char) == ChCurrent) { // message: unterminated string throw new ScanningException(); } } ChPosition++; break; } #endregion When I run test: [Test] [ExpectedException(typeof(ScanningException))] public void ScanDoubleQuotedStrings() { this.Scanner.Run(@"""Hello Language Design""", default(System.Int32)); this.Scanner.Run(@"""Is there any problems with the """"strings""""?""", default(System.Int32)); this.Scanner.Run(@"""v#:';?325;.<>,|+_)""(*&^%$#@![]{}\|-_=""", default(System.Int32)); while(0 != this.Scanner.TokensCount - 1) { Assert.AreEqual(Token.TokenClass.StringLiteral, this.Scanner.NextToken.Class); } } It passes with success.. while I'm expecting to have an exception according to unmatched " mark in this.Scanner.Run(@"""v#:';?325;.<>,|+_)""(*&^%$#@![]{}\|-_=""", default(System.Int32)); Can anyone explain where is my mistake or give an advice on algorithm.

    Read the article

  • C#: How to detect . in string and insert a space after it/How to insert space after n chars?

    - by Sam Gentile
    Suppose I have a long string like "4600airportburlingame150anzablvd.burlingamecalifornia94010". My code is breaking on this string. This is UNUSUAL. 99% of entries will NOT have a period. The CSS in the browser wraps IF there are spaces in the string and there isn't any here. How do I detect the period (".") and insert a space directly after it? Remember 99% of strings will NOT have a period in them. The code has to detect if it has a period and if so, do the insertion, otherwise not. If I determine a maximum string length, how do I insert a space at some length? Thanks

    Read the article

  • Convert array to CSV/TSV-formated string in Python.

    - by dreeves
    Python provides csv.DictWriter for outputting CSV to a file. What is the simplest way to output CSV to a string or to stdout? For example, given a 2D array like this: [["a b c", "1,2,3"], ["i \"comma-heart\" you", "i \",heart\" u, too"]] return the following string: "a b c, \"1, 2, 3\"\n\"i \"\"comma-heart\"\" you\", \"i \"\",heart\"\" u, too\"" which when printed would look like this: a b c, "1,2,3" "i ""heart"" you", "i "",heart"" u, too" (I'm taking csv.DictWriter's word for it that that is in fact the canonical way to output that array as CSV. Excel does parse it correctly that way, though Mathematica does not. From a quick look at the wikipedia page on CSV it seems Mathematica is wrong.) One way would be to write to a temp file with csv.DictWriter and read it back with csv.DictReader. What's a better way? TSV instead of CSV It also occurs to me that I'm not wedded to CSV. TSV would make a lot of the headaches with delimiters and quotes go away: just replace tabs with spaces in the entries of the 2D array and then just intersperse tabs and newlines and you're done. Let's include solutions for both TSV and CSV in the answers to make this as useful as possible for future searchers.

    Read the article

  • Number of simple mutations to change one string to another?

    - by mstksg
    Hi; I'm sure you've all heard of the "Word game", where you try to change one word to another by changing one letter at a time, and only going through valid English words. I'm trying to implement an A* Algorithm to solve it (just to flesh out my understanding of A*) and one of the things that is needed is a minimum-distance heuristic. That is, the minimum number of one of these three mutations that can turn an arbitrary string a into another string b: 1) Change one letter for another 2) Add one letter at a spot before or after any letter 3) Remove any letter Examples aabca => abaca: aabca abca abaca = 2 abcdebf => bgabf: abcdebf bcdebf bcdbf bgdbf bgabf = 4 I've tried many algorithms out; I can't seem to find one that gives the actual answer every time. In fact, sometimes I'm not sure if even my human reasoning is finding the best answer. Does anyone know any algorithm for such purpose? Or maybe can help me find one? Thanks.

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >