Search Results

Search found 49435 results on 1978 pages for 'query string'.

Page 27/1978 | < Previous Page | 23 24 25 26 27 28 29 30 31 32 33 34  | Next Page >

  • Finding ALL positions of a substring in a large string in C#

    - by Tommy
    Alright, so what i have, is a large string i need to parse, and what i need to happen, is find all the instances of extract"(me,i-have lots. of]punctuation, and store them to a list. So say this piece of string was in the beginning and middle of the larger string, both of them would be found, and their index's would be added to the List. and the List would contain 0 and the other index whatever it would be. Ive been playing around, and the string.IndexOf does almost what i'm looking for, and ive written some code. But i cant seem to get it to work: List<int> inst = new List<int>(); int index = 0; while (index < source.LastIndexOf("extract\"(me,i-have lots. of]punctuation", 0) + 39) { int src = source.IndexOf("extract\"(me,i-have lots. of]punctuation", index); inst.Add(src); index = src + 40; } inst = The list source = The large string Any better ideas?

    Read the article

  • How can I manually interpolate string escapes in a Perl string?

    - by Ryan Thompson
    In perl suppose I have a string like 'hello\tworld\n', and what I want is: 'hello world ' That is, "hello", then a literal tab character, then "world", then a literal newline. Or equivalently, "hello\tworld\n" (note the double quotes). In other words, is there a function for taking a string with escape sequences and returning an equivalent string with all the escape sequences interpolated?

    Read the article

  • Property value of a String object in JavaScript

    - by naivists
    As far as I understand, every string is an object in Javascript. Still, it "does not work" as I expect it to be: var a="abc"; //here we get a new string object a.b = 123; //I seem to declare a property "b" of that object alert(a.b); //alerts "undefined" However, if I try to define a string in the "wrong way", everything works as expected var a=new String("abc"); // a.b = 123; alert(a.b); //alerts "123" Why is that so?

    Read the article

  • Get index of nth occurrence of char in a string

    - by StickFigs
    I'm trying to make a function that returns the index of the Nth occurrence of a given char in a string. Here is my attempt: private int IndexOfNth(string str, char c, int n) { int index = str.IndexOf(c) + 1; if (index >= 0) { string temp = str.Substring(index, str.Length - index); for (int j = 1; j < n; j++) { index = temp.IndexOf(c) + 1; if (index < 0) { return -1; } temp = temp.Substring(index, temp.Length - index); } index = index + (str.Length); } return index; } This should find the first occurrence, chop off that front part of the string, find the first occurrence from the new substring, and on and on until it gets the index of the nth occurrence. However I failed to consider how the index of the final substring is going to be offset from the original actual index in the original string. How do I make this work? Also as a side question, if I want the char to be the tab character do I pass this function '\t' or what?

    Read the article

  • passing string literal to std::map::find(..)

    - by ra170
    I've got a std::map. I'm passing string literal to find method. Obviously, I can pass a string literal such as .find("blah"); However, I wanted to declare it upfront, instead of hardcoding the string, so I have couple of choices now: const std::string mystring = "blah"; const char mystring[] = "blah"; static const char * mystring = "blah"; They all work. (or at least compile). My question is, which one should I use? what's the advantage/distavantage over of the other?

    Read the article

  • StringBuffer wont read whole stream into a string (JAVA/Android)

    - by Levara
    Hi all! I'm making an android program that retrieves content of a webpage using HttpURLConnection. I'm new to both Java and Android. Problem is: Reader reads whole page source, but in the last while iteration it doesn't append to stringBuffer that last part. Using debbuger I have determined that, in the last loop iteration, string buff is created, but stringBuffer just doesnt append it. I need to parse retrieved content. Is there any better way to handle the content for parsing than using strings. I've read on numerous other sites that string size in Java is limited only by available heap size. I've tried with StringBuilder too. Anyone know what could be the problem. Btw feel free to suggest any improvements to the code. Thanks! URL u; try { u = new URL("http://feeds.timesonline.co.uk/c/32313/f/440134/index.rss"); HttpURLConnection c = (HttpURLConnection) u.openConnection(); c.setRequestProperty("User-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; InfoPath.1; .NET CLR 2.0.50727)"); c.setRequestMethod("GET"); c.setDoOutput(true); c.setReadTimeout(3000); c.connect(); StringBuffer stringBuffer = new StringBuffer(""); InputStream in = c.getInputStream(); InputStreamReader inp = new InputStreamReader(in); BufferedReader reader = new BufferedReader(inp); char[] buffer = new char[3072]; int len1 = 0; while ( (len1 = reader.read(buffer)) != -1 ) { String buff = new String(buffer,0,len1); stringBuffer.append(buff); } String stranica = new String(stringBuffer); c.disconnect(); reader.close(); inp.close(); in.close();

    Read the article

  • Efficient way in Python to remove an element from a comma-separated string

    - by ensnare
    I'm looking for the most efficient way to add an element to a comma-separated string while maintaining alphabetical order for the words: For example: string = 'Apples, Bananas, Grapes, Oranges' subtraction = 'Bananas' result = 'Apples, Grapes, Oranges' Also, a way to do this but while maintaining IDs: string = '1:Apples, 4:Bananas, 6:Grapes, 23:Oranges' subtraction = '4:Bananas' result = '1:Apples, 6:Grapes, 23:Oranges' Sample code is greatly appreciated. Thank you so much.

    Read the article

  • Formatting my String

    - by pringlesinn
    I need to write currency values like $35.40 (thirty five dollars and forty cents) and after that, i want to write some "****" so at the end it will be: thirty five dollars and forty cents********* in a maximun of 100 characters I've asked a question about something very likely but I couldn't understand the main command. String format = String.format("%%-%ds", 100); String valorPorExtenso = String.format(format, new Extenso(tituloTO.getValor()).toString()); What do I need to change on format to put *** at the end of my sentence? The way it is now it puts spaces.

    Read the article

  • convert string to dict using list comprehension in python

    - by Pavel
    I have came across this problem a few times and can't seem to figure out a simple solution. Say I have a string string = "a=0 b=1 c=3" I want to convert that into a dictionary with a, b and c being the key and 0, 1, and 3 being their respective values (converted to int). Obviously I can do this: list = string.split() dic = {} for entry in list: key, val = entry.split('=') dic[key] = int(val) But I don't really like that for loop, It seems so simple that you should be able to convert it to some sort of list comprehension expression. And that works for slightly simpler cases where the val can be a string. dic = dict([entry.split('=') for entry in list]) However, I need to convert val to an int on the fly and doing something like this is syntactically incorrect. dic = dict([[entry[0], int(entry[1])] for entry.split('=') in list]) So my question is: is there a way to eliminate the for loop using list comprehension? If not, is there some built in python method that will do that for me?

    Read the article

  • How can get unique values from data table using dql?

    - by piemesons
    I am having a table in which there is a column in which various values are stored.i want to retrieve unique values from that table using dql. Doctrine_Query::create() ->select('rec.school') ->from('Records rec') ->where("rec.city='$city' ") ->execute(); Now i want only unique values. Can anybody tell me how to do that... Edit Table Structure: CREATE TABLE IF NOT EXISTS `records` ( `id` int(11) NOT NULL AUTO_INCREMENT, `state` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `city` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `school` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=16334 ; This is the Query I am using: Doctrine_Query::create() ->select('DISTINCT rec.city') ->from('Records rec') ->where("rec.state = '$state'") // ->getSql(); ->execute(); Generting Sql for this gives me: SELECT DISTINCT r.id AS r__id, r.city AS r__city FROM records r WHERE r.state = 'AR' Now check the sql generated:::: DISTINCT is on 'id' column where as i want Distinct on city column. Anybody know how to fix this. EDIT2 Id is unique cause its an auto incremental value.Ya i have some real duplicates in city column like: Delhi and Delhi. Right.. Now when i am trying to fetch data from it, I am getting Delhi two times. How can i make query like this: select DISTINCT rec.city where state="xyz"; Cause this will give me the proper output. EDIT3: Anybody who can tell me how to figure out this query..???

    Read the article

  • implement string class with custom behavior

    - by truman
    In one of our class sir said that template allows one to customize behavior of class, and then he gave example of string class, that with few lines of code we can customize string class from STL, as in, we can make it to treat 'a' and 'z' same, 'b' and 'y' same, 'c' and 'x' same and so on. Similary 'A' and 'Z' same etc. "abc" == "zyx" is true; "Abc" == "zyx" is false; "Abc == "Zyx" is true; etc I was thinking of implementing such string class, but I am not able to do so. How can we implement such string class using templates?

    Read the article

  • Linq query: append column to query results

    - by jrubengb
    I am trying to figure out how to append a column to Linq query results based on the max value of the query. Essentially, I want to create an EnumerableRowCollection of DataRows that would include a max value record with the same value for each record. So if i have a hundred records returned through the query, I want to next calculate the max value of one of the fields, then append that max value to the original query table: DataTable dt = new DataTable(); dt = myDataSet.myDataTable; EnumerableRowCollection<DataRow> qrySelectRecords = (from d in dt.AsEnumerable() where d.Field<DateTime>("readingDate") >= startDate && g.Field<DateTime>("readingDate") <= endDate select d); Here's where I need help: double maxValue = qrySelectRecords.Field<double>("field1").Max(); foreach (DataRow dr in qrySelectRecords) { qrySelectRecords.Column.Append(maxValue) }

    Read the article

  • How to find which delimiter was used during string split (VB.NET)

    - by typoknig
    Hi all, lets say I have a string that I want to split based on several characters, like ".", "!", and "?". How do I figure out which one of those characters split my string so I can add that same character back on to the end of the split segments in question? Dim linePunctuation as Integer = 0 Dim myString As String = "some text. with punctuation! in it?" For i = 1 To Len(myString) If Mid$(entireFile, i, 1) = "." Then linePunctuation += 1 Next For i = 1 To Len(myString) If Mid$(entireFile, i, 1) = "!" Then linePunctuation += 1 Next For i = 1 To Len(myString) If Mid$(entireFile, i, 1) = "?" Then linePunctuation += 1 Next Dim delimiters(3) As Char delimiters(0) = "." delimiters(1) = "!" delimiters(2) = "?" currentLineSplit = myString.Split(delimiters) Dim sentenceArray(linePunctuation) As String Dim count As Integer = 0 While linePunctuation > 0 sentenceArray(count) = currentLineSplit(count)'Here I want to add what ever delimiter was used to make the split back onto the string before it is stored in the array.' count += 1 linePunctuation -= 1 End While

    Read the article

  • How Optimize sql query make it faster

    - by user502083
    Hello every one : I have a very simple small database, 2 of tables are: Node (Node_ID, Node_name, Node_Date) : Node_ID is primary key Citation (Origin_Id, Target_Id) : PRIMARY KEY (Origin_Id, Target_Id) each is FK in Node Now I write a query that first find all citations that their Origin_Id has a specific date and then I want to know what are the target dates of these records. I'm using sqlite in python the Node table has 3000 record and Citation has 9000 records, and my query is like this in a function: def cited_years_list(self, date): c=self.cur try: c.execute("""select n.Node_Date,count(*) from Node n INNER JOIN (select c.Origin_Id AS Origin_Id, c.Target_Id AS Target_Id, n.Node_Date AS Date from CITATION c INNER JOIN NODE n ON c.Origin_Id=n.Node_Id where CAST(n.Node_Date as INT)={0}) VW ON VW.Target_Id=n.Node_Id GROUP BY n.Node_Date;""".format(date)) cited_years=c.fetchall() self.conn.commit() print('Cited Years are : \n ',str(cited_years)) except Exception as e: print('Cited Years retrival failed ',e) return cited_years Then I call this function for some specific years, But it's crazy slowwwwwwwww :( (around 1 min for a specific year) Although my query works fine, it is slow. would you please give me a suggestion to make it faster? I'd appreciate any idea about optimizing this query :) I also should mention that I have indices on Origin_Id and Target_Id, so the inner join should be pretty fast, but it's not!!!

    Read the article

  • Find and replace text in a string using C#

    - by Joey Morani
    Anyone know how I would find & replace text in a string? Basically I have two strings: string firstS = "/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDABQODxIPDRQSERIXFhQYHzMhHxwcHz8tLyUzSkFOTUlBSEZSXHZkUldvWEZIZoxob3p9hIWET2ORm4+AmnaBhH//2wBDARYXFx8bHzwhITx/VEhUf39/f39/f39/f39/f39/f39/f39/f39/f39/f39/f39/f39/f39/f39/f39/f39/f3//"; string secondS = "abcdefg2wBDABQODxIPDRQSERIXFh/f39/f39/f39/f39/f39/f39/f39/f39/f39/f39/f39/f39/f39/f39/f39/abcdefg"; I want to search firstS to see if it contains any sequence of characters that's in secondS and then replace it. It also needs to be replaced with the number of replaced characters in squared brackets: [NUMBER-OF-CHARACTERS-REPLACED] For example, because firstS and secondS both contain "2wBDABQODxIPDRQSERIXFh" and "/f39/f39/f39/f39/f39/f39/f39/f39/f39/f39/f39/f39/f39/f39/f39/" they would need to be replaced. So then firstS becomes: string firstS = "/9j/4AAQSkZJRgABAQEAYABgAAD/[22]QYHzMhHxwcHz8tLyUzSkFOTUlBSEZSXHZkUldvWEZIZoxob3p9hIWET2ORm4+AmnaBhH//2wBDARYXFx8bHzwhITx/VEhUf39[61]f3//"; Hope that makes sense. I think I could do this with Regex, but I don't like the inefficiency of it. Does anyone know of another, faster way?

    Read the article

  • Query returning related assets

    - by GMo
    I have 2 tables, one is an assets table which holds digital assets (e.g. article, images etc), the 2nd table is an asset_links table which maps 1-1 relationships between assets contained within the assets table. Here are the table definitions: Asset +---------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +---------------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | source | varchar(255) | YES | | NULL | | | title | varchar(255) | YES | | NULL | | | date_created | datetime | YES | | NULL | | | date_embargo | datetime | YES | | NULL | | | date_expires | datetime | YES | | NULL | | | date_updated | datetime | YES | | NULL | | | keywords | varchar(255) | YES | | NULL | | | status | int(11) | YES | | NULL | | | priority | int(11) | YES | | NULL | | | fk_site | int(11) | YES | MUL | NULL | | | resource_type | varchar(255) | YES | | NULL | | | resource_id | int(11) | YES | | NULL | | | fk_user | int(11) | YES | MUL | NULL | | +---------------+--------------+------+-----+---------+----------------+ Asset_links +-----------+---------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-----------+---------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | asset_id1 | int(11) | YES | | NULL | | | asset_id2 | int(11) | YES | | NULL | | +-----------+---------+------+-----+---------+----------------+ In the asset_links table there are the following rows: 1 - 3, 1 - 4, 2 - 10, 2 - 56 I am looking to write one query which will return all assets which satisfy any asset search criteria and within the same query return all of the linked asset data for linked assets for that asset. e.g. The query returning assets 1 and 2 would return : Asset 1 attributes - Asset 3 attributes - Asset 4 attributes Asset 2 attributes - Asset 10 attributes - Asset 56 attributes What is the best way to write the query?

    Read the article

  • std::string constructor corrupts pointer

    - by computergeek6
    I have an Entity class, which contains 3 pointers: m_rigidBody, m_entity, and m_parent. Somewhere in Entity::setModel(std::string model), it's crashing. Apparently, this is caused by bad data in m_entity. The weird thing is that I nulled it in the constructor and haven't touched it since then. I debugged it and put a watchpoint on it, and it comes up that the m_entity member is being changed in the constructor for std::string that's being called while converting a const char* into an std::string for the setModel call. I'm running on a Mac, if that helps (I think I remember some problem with std::string on the Mac). Any ideas about what's going on?

    Read the article

  • Most efficient way to remove special characters from string

    - by ObiWanKenobi
    I want to remove all special characters from a string. Allowed characters are A-Z (uppercase or lowercase), numbers (0-9), underscore (_), or the dot sign (.). I have the following, it works but I suspect (I know!) it's not very efficient: public static string RemoveSpecialCharacters(string str) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < str.Length; i++) { if ((str[i] >= '0' && str[i] <= '9') || (str[i] >= 'A' && str[i] <= 'z' || (str[i] == '.' || str[i] == '_'))) sb.Append(str[i]); } return sb.ToString(); } What is the most efficient way to do this? What would a regular expression look like, and how does it compare with normal string manipulation? The strings that will be cleaned will be rather short, usually between 10 and 30 characters in length.

    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

  • Sub Query making Query slow.

    - by Muhammad Kashif Nadeem
    Please copy and paste following script. DECLARE @MainTable TABLE(MainTablePkId int) INSERT INTO @MainTable SELECT 1 INSERT INTO @MainTable SELECT 2 DECLARE @SomeTable TABLE(SomeIdPk int, MainTablePkId int, ViewedTime1 datetime) INSERT INTO @SomeTable SELECT 1, 1, DATEADD(dd, -10, getdate()) INSERT INTO @SomeTable SELECT 2, 1, DATEADD(dd, -9, getdate()) INSERT INTO @SomeTable SELECT 3, 2, DATEADD(dd, -6, getdate()) DECLARE @SomeTableDetail TABLE(DetailIdPk int, SomeIdPk int, Viewed INT, ViewedTimeDetail datetime) INSERT INTO @SomeTableDetail SELECT 1, 1, 1, DATEADD(dd, -7, getdate()) INSERT INTO @SomeTableDetail SELECT 2, 2, NULL, DATEADD(dd, -6, getdate()) INSERT INTO @SomeTableDetail SELECT 3, 2, 2, DATEADD(dd, -8, getdate()) INSERT INTO @SomeTableDetail SELECT 4, 3, 1, DATEADD(dd, -6, getdate()) SELECT m.MainTablePkId, (SELECT COUNT(Viewed) FROM @SomeTableDetail), (SELECT TOP 1 s2.ViewedTimeDetail FROM @SomeTableDetail s2 INNER JOIN @SomeTable s1 ON s2.SomeIdPk = s1.SomeIdPk WHERE s1.MainTablePkId = m.MainTablePkId) FROM @MainTable m Above given script is just sample. I have long list of columns in SELECT and around 12+ columns in Sub Query. In my From clause there are around 8 tables. To fetch 2000 records full query take 21 seconds and if I remove Subquiries it just take 4 seconds. I have tried to optimize query using 'Database Engine Tuning Advisor' and on adding new advised indexes and statistics but these changes make query time even bad. Note: As I have mentioned that this is test data to explain my question the real data has lot of tables joins columns but without Sub-Query the results us fine. Any help thanks.

    Read the article

  • C++: Define simple string?

    - by Jason
    This thing is really wracking my mind. I'm learning C++ and I wanted to define a constant that I can use in another function, A short answer on how to do this will be fine.. Lets say at the beginning of my code I want to define this constant: //After #includes bool OS = 1; //1 = linux if (OS) { const ??? = "clear"; } else { const ??? = "cls"; } I don't know what type to use to define the "clear" string... I'm so confused. Later on I want to use it within a function: int foo() { system(::cls); //:: for global return 0; } How would I define the string up top, and use the string down below? I heard char only had one character and things... I'm not sure how to use , since it says it's converting string into const char or something.

    Read the article

< Previous Page | 23 24 25 26 27 28 29 30 31 32 33 34  | Next Page >