Search Results

Search found 37183 results on 1488 pages for 'string conversion'.

Page 16/1488 | < Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >

  • Java multiline string

    - by skiphoppy
    Coming from Perl, I sure am missing the "here-document" means of creating a multi-line string in source code: $string = <<"EOF" # create a three line string text text text EOF In Java I have to have cumbersome quotes and plus signs on every line as I concatenate my multiline string from scratch. What are some better alternatives? Define my string in a properties file? Edit: Two answers say StringBuilder.append() is preferable to the plus notation. Could anyone elaborate as to why they think so? It doesn't look more preferable to me at all. I'm looking for away around the fact that multiline strings are not a first-class language construct, which means I definitely don't want to replace a first-class language construct (string concatenation with plus) with method calls. Edit: To clarify my question further, I'm not concerned about performance at all. I'm concerned about maintainability and design issues.

    Read the article

  • How do I truncate a .NET string?

    - by Steve Guidi
    I apologize for such a question that likely has a trivial solution, but I strangely could not find a concise API for this problem. Essentially, I would like to truncate a string such that it its length is not longer than a given value. I am writing to a database table and want to ensure that the values I write meet the constraint of the column's datatype. For instance, it would be nice if I could write the following: string NormalizeLength(string value, int maxLength) { return value.Substring(0, maxLength); } Unfortunately, this raises an exception because maxLength exceeds the string boundaries. Of course, I could write a function like the following, but I was hoping that something like this already exists. string NormalizeLength(string value, int maxLength) { return value.Length <= maxLength ? value : value.Substring(0, maxLength); } Where is the elusive API that performs this task? Is there one?

    Read the article

  • string manipulation without alloc mem in c

    - by Mike
    I'm wondering if there is another way of getting a sub string without allocating memory. To be more specific, I have a string as: const char *str = "9|0\" 940 Hello"; Currently I'm getting the 940, which is the sub-string I want as, char *a = strstr(str,"9|0\" "); char *b = substr(a+5, 0, 3); // gives me the 940 Where substr is my sub string procedure. The thing is that I don't want to allocate memory for this by calling the sub string procedure. Is there a much easier way?, perhaps by doing some string manipulation and not alloc mem. I'll appreciate any feedback.

    Read the article

  • C++ String manipulation isn't making sense to me...

    - by Andrew Bolster
    I am trying some of the Stanford SEE courses online to learn some new languages; this particular assignment has to do with removing substrings from strings. What I've got so far is below, but if text = "hello hello" and remove ="el", it gets stuck in a loop, but if i change text to text = "hello hllo", it works, making me think I'm doing something obviously stupid. There is a stipulation in the assignment not to modify the incoming strings, and instead to return a new string. string CensorString1(string text, string remove){ string returned; size_t found=0, lastfound=0; found = (text.substr(lastfound,text.size())).find(remove); while (string::npos != found ){ returned += text.substr(lastfound,found); lastfound = found + remove.size(); found = (text.substr(lastfound,text.size())).find(remove); } returned += text.substr(lastfound,found); return returned; } Guidance would be appreciated :-) Thanks

    Read the article

  • About the String#substring() method

    - by alain.janinm
    If we take a look at the String#substring method implementation : new String(offset + beginIndex, endIndex - beginIndex, value); We see that a new String is created with the same original content (parameter char [] value). So the workaround is to use new String(toto.substring(...)) to drop the reference to the original char[] value and make it eligible for GC (if no more references exist). I would like to know if there is a special reason that explain this implementation. Why the method doesn't create herself the new shorter String and why she keeps the full original value instead? The other related question is : should we always use new String(...) when dealing with substring?

    Read the article

  • String intern puzzles

    - by Yob
    On this blog I found interesting String puzzles: --- Quote --- String te = "te", st = "st"; //"test".length(); String username = te + st; username.intern(); System.out.println("String object the same is: " + (username == "test")); prints String object the same is: true but uncomment the "test".length(); line and it prints String object the same is: false --- EoQ --- Being honest I don't understand why the outputs are different. Could you please explain me what's the cause of such behaviour?

    Read the article

  • string manipulations in C

    - by Vivek27
    Following are some basic questions that I have with respect to strings in C. If string literals are stored in read-only data segment and cannot be changed after initialisation, then what is the difference between the following two initialisations. char *string = "Hello world"; const char *string = "Hello world"; When we dynamically allocate memory for strings, I see the following allocation is capable enough to hold a string of arbitary length.Though this allocation work, I undersand/beleive that it is always good practice to allocate the actual size of actual string rather than the size of data type.Please guide on proper usage of dynamic allocation for strings. char *string = (char *)malloc(sizeof(char));

    Read the article

  • Making uppercase of std::string

    - by Daniel K.
    Which implementation do you think is better? std::string ToUpper( const std::string& source ) { std::string result; result.reserve( source.length() ); std::transform( source.begin(), source.end(), result.begin(), std::ptr_fun<int, int>( std::toupper ) ); return result; } and... std::string ToUpper( const std::string& source ) { std::string result( source.length(), '\0' ); std::transform( source.begin(), source.end(), result.begin(), std::ptr_fun<int, int>( std::toupper ) ); return result; } Difference is that the first one uses reserve method after the default constructor, but the second one uses the constructor accepting the number of characters.

    Read the article

  • Why is Java String indexOf failing?

    - by Binaryrespawn
    Hi all, this must be quite simple but I am having great difficulty. You see I am trying to find a string within another string as follows. e = input.indexOf("-->"); s = input.indexOf("<!--"); input = input.replace(input.substring(s, e + 3), " "); The integers e and s are returning -1 in that it was not found and this is causing the replace method to fail. The test string I am using is "Chartered Certified<!--lol--> Accountants (ACCA)". I tried to creat a new string object and pass in the string as an argument as follows e=input.indexOf(new String("<!--")); This yielded the same result. Any ideas ?

    Read the article

  • .NET Format a string with fixed spaces

    - by treant
    Does the .NET String.Format method allow placement of a string at a fixed position within a fixed length string. " String Goes Here" " String Goes Here " "String Goes Here " How is this done using .NET? Edit - I have tried Format/PadLeft/PadRight to death. They do not work. I don't know why. I ended up writing my own function to do this. Edit - I made a mistake and used a colon instead of a comma in the format specifier. Should be "{0,20}". Thanks for all of the excellent and correct answers.

    Read the article

  • Question about the String.replaceAll() and String.replaceFirst() method.

    - by Java Doe
    I need to do a simple string replace operation on a segment of string. I ran into the following issue and hope to get some advice. In the original string I got, I can replace the string such as to something else. BUT, in the same original string, if I want to replace a much long string such as the following, it won’t work. Nothing gets replaced after the call. <div class="more"><a href="http://SERVER_name/profiles/atom/mv/theboard/entries/related.do?email=xyz.com&ps=20&since=1273518953218&sinceEntryId=abc-def-123-456">More...</a></div> I tried these two methods: originalString.replaceFirst(moreTag, newContent); originalString.replaceAll(moreTag, newContent); Thanks in advance.

    Read the article

  • How to optimize process of outlook files (*msg) conversion to .pdf?

    - by Lilly
    The aim is to convert several messages from Microsoft Outlook (2003 and/or 2007 versions) to .pdf files. Condition: One message should generate a corresponding single pdf file. If possible, pdf file should be named with date format YYYY-MM-DD (e.g. 2011-02-16.pdf). The current process, limited by softwares such as CutePDF, requires the conversion performed one message at a time. I'm looking for a solution that allows the conversion of several messages at once, but under the condition abovementioned (mainly: one message = one pdf file).

    Read the article

  • Excel equivilant of java's String.contains(String otherString)

    - by corsiKa
    I have a cell that has a fairly archaic String. (It's the mana cost of a Magic: the Gathering spell.) Examples are 3g, 2gg, 3ur, and bg. There are 5 possible letters (g w u b r). I have 5 columns and would like to count at the bottom how many of each it contains. So my spreadsheet might look like this A B C D E F G +-------------------------------------------- 1|Name Cost G W U B R 2|Centaur Healer 1gw 1 1 0 0 0 3|Sunspire Griffin 1ww 0 1 0 0 0 // just 1, even though 1ww 4|Rakdos Shred-Freak {br}{br} 0 0 0 1 1 Basically, I want something that looks like =if(contains($A2,C$1),1,0) and I can drag it across all 5 columns and down all 270 some cards. (Those are actual data, by the way. It's not mocked :-) .) In Java I would do this: String[] colors = { "B", "G", "R", "W", "U" }; for(String color : colors) { System.out.print(cost.toUpperCase().contains(color) ? 1 : 0); System.out.print("\t"); } Is there something like this in using Excel 2010. I tried using find() and search() and they work great if the color exists. But if the color doesn't exist, it returns #value - so I get 1 1 #value #value #value instead of 1 1 0 0 0 for, example, Centaur Healer (row 2). The formula used was if(find($A2,C$1) > 0, 1, 0).

    Read the article

  • Converting List<String> to String[] in Java

    - by Christian
    How do I convert a list into an array? The following code returns an error. public static void main(String[] args) { List<String> strlist = new ArrayList<String>(); strlist.add("sdfs1"); strlist.add("sdfs2"); String[] strarray = (String[]) strlist.toArray(); System.out.println(strarray); }

    Read the article

  • i want to return List<DictionaryClass<string,string>> from web service but getting error for IDictio

    - by girish
    [WebMethod] public List<DictionaryClass<string,string>> GetDataByModuleDictionary(string ModuleName) { return BAL_GeneralService.GetDataByModuleDictionary(ModuleName); } here i m getting the following error... The type DictionaryClass`2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] is not supported because it implements IDictionary.

    Read the article

  • Loosely coupled implicit conversion

    - by ltjax
    Implicit conversion can be really useful when types are semantically equivalent. For example, imagine two libraries that implement a type identically, but in different namespaces. Or just a type that is mostly identical, except for some semantic-sugar here and there. Now you cannot pass one type into a function (in one of those libraries) that was designed to use the other, unless that function is a template. If it's not, you have to somehow convert one type into the other. This should be trivial (or otherwise the types are not so identical after-all!) but calling the conversion explicitly bloats your code with mostly meaningless function-calls. While such conversion functions might actually copy some values around, they essentially do nothing from a high-level "programmers" point-of-view. Implicit conversion constructors and operators could obviously help, but they introduce coupling, so that one of those types has to know about the other. Usually, at least when dealing with libraries, that is not the case, because the presence of one of those types makes the other one redundant. Also, you cannot always change libraries. Now I see two options on how to make implicit conversion work in user-code: The first would be to provide a proxy-type, that implements conversion-operators and conversion-constructors (and assignments) for all the involved types, and always use that. The second requires a minimal change to the libraries, but allows great flexibility: Add a conversion-constructor for each involved type that can be externally optionally enabled. For example, for a type A add a constructor: template <class T> A( const T& src, typename boost::enable_if<conversion_enabled<T,A>>::type* ignore=0 ) { *this = convert(src); } and a template template <class X, class Y> struct conversion_enabled : public boost::mpl::false_ {}; that disables the implicit conversion by default. Then to enable conversion between two types, specialize the template: template <> struct conversion_enabled<OtherA, A> : public boost::mpl::true_ {}; and implement a convert function that can be found through ADL. I would personally prefer to use the second variant, unless there are strong arguments against it. Now to the actual question(s): What's the preferred way to associate types for implicit conversion? Are my suggestions good ideas? Are there any downsides to either approach? Is allowing conversions like that dangerous? Should library implementers in-general supply the second method when it's likely that their type will be replicated in software they are most likely beeing used with (I'm thinking of 3d-rendering middle-ware here, where most of those packages implement a 3D vector).

    Read the article

  • Best way to split a string by word (SQL Batch separator)

    - by Paul Kohler
    I have a class I use to "split" a string of SQL commands by a batch separator - e.g. "GO" - into a list of SQL commands that are run in turn etc. ... private static IEnumerable<string> SplitByBatchIndecator(string script, string batchIndicator) { string pattern = string.Concat("^\\s*", batchIndicator, "\\s*$"); RegexOptions options = RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Multiline; foreach (string batch in Regex.Split(script, pattern, options)) { yield return batch.Trim(); } } My current implementation uses a Regex with yield but I am not sure if it's the "best" way. It should be quick It should handle large strings (I have some scripts that are 10mb in size for example) The hardest part (that the above code currently does not do) is to take quoted text into account Currently the following SQL will incorrectly get split: var batch = QueryBatch.Parse(@"-- issue... insert into table (name, desc) values('foo', 'if the go is on a line by itself we have a problem...')"); Assert.That(batch.Queries.Count, Is.EqualTo(1), "This fails for now..."); I have thought about a token based parser that tracks the state of the open closed quotes but am not sure if Regex will do it. Any ideas!?

    Read the article

  • Returning the element number of the longest string in an array

    - by JohnRoberts
    I'm trying to get the longestS method to take the user-inputted array of strings, then return the element number of the longest string in that array. I got it to the point where I was able to return the number of chars in the longest string, but I don't believe that will work for what I need. My problem is that I keep getting incompatible type errors when trying to figure this out. I don't understand the whole data type thing with strings yet. It's confusing me how I go about return a number of the array yet the array is of strings. The main method is fine, I got stuck on the ???? part. { public static void main(String [] args) { Scanner inp = new Scanner( System.in ); String [] responseArr= new String[4]; for (int i=0; i<4; i++) { System.out.println("Enter string "+(i+1)); responseArr[i] = inp.nextLine(); } int highest=longestS(responseArr); } public static int longestS(String[] values) { int largest=0 for( int i = 1; i < values.length; i++ ) { if ( ????? ) } return largest; } }

    Read the article

  • [java] Returning the element number of the longest string in an array

    - by JohnRoberts
    Hoookay, so. I'm trying to get the longestS method to take the user-inputted array of strings, then return the element number of the longest string in that array. I got it to the point where I was able to return the number of chars in the longest string, but I don't believe that will work for what I need. My problem is that I keep getting incompatible type errors when trying to figure this out. I don't understand the whole data type thing with strings yet. It's confusing me how I go about return a number of the array yet the array is of strings. The main method is fine, I got stuck on the ???? part. { public static void main(String [] args) { Scanner inp = new Scanner( System.in ); String [] responseArr= new String[4]; for (int i=0; i<4; i++) { System.out.println("Enter string "+(i+1)); responseArr[i] = inp.nextLine(); } int highest=longestS(responseArr); } public static int longestS(String[] values) { int largest=0 for( int i = 1; i < values.length; i++ ) { if ( ????? ) } return largest; } }

    Read the article

  • Circumvent c++ null-terminated string frustration

    - by ypnos
    I'm using boost::program_options and it suffers from the same as many other c++ libs, even std itself: It still uses C-style null-terminated strings, because nobody really likes the weak std::string. The method in question is: options_description_easy_init& operator()(const char* name, const value_semantic* s, const char* description); The typical use case is just fine: options.add_options() ("graphical", bool_switch(&isGraphical)->default_value(false), "Show any graphical output during runtime") However, I need the name of the option to be set dynamically. The reason is that in some cases I nead a custom prefix, which is added to the string by my function std::string key(const std::string& k): options.add_options() (key("graphical"), bool_switch(&isGraphical)->default_value(false), "Show any graphical output during runtime") This fails. I could now use c_str() on the std::string but that's evil -- I don't know how long program_options keeps the variable around and if my string is still alive when needed. I could also reserve memory in a buffer etc. and hand in that. The buffer is never freed and it sucks/is evil. Is there anything else I can do to circumvent the C-style string mess in this situation?

    Read the article

  • Why doesn't String's hashCode() cache 0?

    - by polygenelubricants
    I noticed in the Java 6 source code for String that hashCode only caches values other than 0. The difference in performance is exhibited by the following snippet: public class Main{ static void test(String s) { long start = System.currentTimeMillis(); for (int i = 0; i < 10000000; i++) { s.hashCode(); } System.out.format("Took %d ms.%n", System.currentTimeMillis() - start); } public static void main(String[] args) { String z = "Allocator redistricts; strict allocator redistricts strictly."; test(z); test(z.toUpperCase()); } } Running this in ideone.com gives the following output: Took 1470 ms. Took 58 ms. So my questions are: Why doesn't String's hashCode() cache 0? What is the probability that a Java string hashes to 0? What's the best way to avoid the performance penalty of recomputing the hash value every time for strings that hash to 0? Is this the best-practice way of caching values? (i.e. cache all except one?) For your amusement, each line here is a string that hash to 0: pollinating sandboxes amusement & hemophilias schoolworks = perversive electrolysissweeteners.net constitutionalunstableness.net grinnerslaphappier.org BLEACHINGFEMININELY.NET WWW.BUMRACEGOERS.ORG WWW.RACCOONPRUDENTIALS.NET Microcomputers: the unredeemed lollipop... Incentively, my dear, I don't tessellate a derangement. A person who never yodelled an apology, never preened vocalizing transsexuals.

    Read the article

  • Jumping onto next string when the condition is met

    - by user98235
    This was a problem related to one of the past topcoder exam problems called HowEasy. Let's assume that we're given a sentence, for instance, "We a1re really awe~~~some" I just wanted to take get rid of every word in the sentence that doesn't contain alphabet characters, so in the above sentence, the desired output would be "We really" The below is the code I wrote (incomplete), and I don't know how to move on to the next string when the condition (the string contains a character that's not alphabet) is met. Could you suggest some revisions or methods that would allow me to do that? vect would be the vector of strings containing the desired output string param; cin>>param; stringstream ss(param); vector<string> vect; string c; while(ss >> c){ for(int i=0; i < c.length(); i++){ if(!(97<=int(c[i])&&int(c[i])<=122) && !(65<=int(c[i])&&int(c[i])<=90)){ //I want to jump onto next string once the above condition is met //and ignore string c; } vect.push_back(c); if (ss.peek() == ' '){ ss.ignore(); } } }

    Read the article

< Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >