Search Results

Search found 44874 results on 1795 pages for 'string format'.

Page 29/1795 | < Previous Page | 25 26 27 28 29 30 31 32 33 34 35 36  | Next Page >

  • C Array of string

    - by Meko
    HI. This is maybe simple question but I want to create two dimensional array and add it string like in java string str = "text" ; string [][] array = new [][] string ; array[i][j] = str ; But in C there is no string .I tried like this but here strcpy() gives error.It returns to assembly code. I am trying to read line by line from text and split line by space and add them to structure.But first I think that I must add each line and row in array and then making iteration and adding to structures fields. static const char filename[] = "student.txt"; FILE *file = fopen ( filename, "r" ); char line [ 128 ]; /* or other suitable maximum line size */ char delims [ ]=" "; char *result =NULL; char list[15]; char arra[128][128]; int i=0; int j=0; struct { char gruppa[10]; char familiya[20]; int uchaste; struct { int firsth; int second; int third; int fourht; int fifth; } exam; }student; for(i=0; i<128; i++) for(j=0; j<128; j++) arra[i][j] = '\0'; for(i=0; i<15; i++) list[i] = '\0'; if ( file != NULL ) { while ( fgets ( line, sizeof line, file ) != NULL ) { result = strtok(line,delims); while (result !=NULL) { strcpy(list,("%s",result)); strcpy(arra[i][j],list); // Here it gives errror j++; result = strtok(NULL,delims); } j=0; i++; } fclose ( file ); } else { perror ( filename ); } getchar(); return 0; }

    Read the article

  • C++ exam question on string class implementation

    - by Carlucho
    I just took an exam where i was asked the following: Write the function body of each of the methods GenStrLen, InsertChar and StrReverse for the given code bellow. You must take into consideration the following; How strings are constructed in C++ The string must not overflow Insertion of character increases its length by 1 An empty string is indicated by StrLen = 0 class Strings { private: char str[80]; int StrLen; public: // Constructor Strings() { StrLen=0; }; // A function for returning the length of the string 'str' int GetStrLen(void) { }; // A function to inser a character 'ch' at the end of the string 'str' void InsertChar(char ch) { }; // A function to reverse the content of the string 'str' void StrReverse(void) { }; }; The answer I gave was something like this (see bellow). My one of problem is that used many extra variables and that makes me believe am not doing it the best possible way, and the other thing is that is not working.... class Strings { private: char str[80]; int StrLen; int index; // *** Had to add this *** public: Strings(){ StrLen=0; } int GetStrLen(void){ for (int i=0 ; str[i]!='\0' ; i++) index++; return index; // *** Here am getting a weird value, something like 1829584505306 *** } void InsertChar(char ch){ str[index] = ch; // *** Not sure if this is correct cuz I was not given int index *** } void StrRevrse(void){ GetStrLen(); char revStr[index+1]; for (int i=0 ; str[i]!='\0' ; i++){ for (int r=index ; r>0 ; r--) revStr[r] = str[i]; } } }; I would appreciate if anyone could explain me toughly what is the best way to have answered the question and why. Also how come my professor closes each class function like " }; " i thought that was only used for ending classes and constructors only. Thanks a lot for your help.

    Read the article

  • C++ stringstream, string, and char* conversion confusion

    - by Graphics Noob
    My question can be boiled down to, where does the string returned from stringstream.str().c_str() live in memory, and why can't it be assigned to a const char*? This code example will explain it better than I can #include <string> #include <sstream> #include <iostream> using namespace std; int main() { stringstream ss("this is a string\n"); string str(ss.str()); const char* cstr1 = str.c_str(); const char* cstr2 = ss.str().c_str(); cout << cstr1 // Prints correctly << cstr2; // ERROR, prints out garbage system("PAUSE"); return 0; } The assumption that stringstream.str().c_str() could be assigned to a const char* led to a bug that took me a while to track down. For bonus points, can anyone explain why replacing the cout statement with cout << cstr // Prints correctly << ss.str().c_str() // Prints correctly << cstr2; // Prints correctly (???) prints the strings correctly? I'm compiling in Visual Studio 2008.

    Read the article

  • php string versus boolean speed test

    - by ae
    I'm looking at trying to optimise a particular function in a php app and foolishly assumed that a boolean lookup in a 'if' statement would be quicker than a string compare. But to check it I put together a short test (see below). To my surprise, the string lookup was quicker. Is there anything wrong with my test (I'm wired on too much coffee so I'm suspicious of my own code)? If not, I would be interested in any comments people have around string versus boolean lookups in php. The result for the first test (boolean lookup) was 0.168 The result for the second test (string lookup) was 0.005 <?php $how_many = 1000000; $counter1 = 0; $counter2 = 0; $abc = array('boolean_lookup'=>TRUE, 'string_lookup'=>'something_else'); $start = microtime(); for($i = 0; $i < $how_many; $i++) { if($abc['boolean_lookup']) { $counter1++; } } echo ($start - microtime()); echo '<hr>'; $start = microtime(); for($i = 0; $i < $how_many; $i++) { if($abc['string_lookup'] == 'something_else') { $counter2++; } } echo ($start - microtime());

    Read the article

  • Parsing multibyte string in PHP

    - by Petr Peller
    I would like to write a (HTML) parser based on state machine but I have doubts how to acctually read/use an input. I decided to load the whole input into one string and then work with it as with an array and hold its index as current parsing position. There would be no problems with single-byte encoding, but in multi-byte encoding each value does not represent a character, but a byte of a character. Example: $mb_string = 'žšcr'; //4 multi-byte characters in UTF-8 for($i=0; $i < 4; $i++) { echo $mb_string[$i], PHP_EOL; } Outputs: L ž L A This means I cannot iterate through the string in a loop to check single characters, because I never know if I am in the middle of an character or not. So the questions are: How do I multi-byte safe read a single character from a string in a performance friendly way? Is it good idea to work with the string as it was an array in this case? How would you read the input?

    Read the article

  • String Comparison containing hyphens not matching

    - by Christo Fur
    I have a method in a url rewriting module that looks like this public bool Match(Uri url) { string x = url.PathAndQuery.ToLowerInvariant(); string y = RuleData.ToLowerInvariant(); return x.Contains(y); } However, it is not returning true for the following values: x = "/xx09-02-09xx"; y = "09-02-09"; but if I write a unit test with the raw strings, like below, it does return true [Test] public void Contains() { string x = "/xx09-02-09xx"; string y = "09-02-09"; Assert.IsTrue(x.Contains(y)); // this returns true } What could be the difference? The encoding? The culture? Have tried removing the ToLowerInvarient(), but that makes no difference have tried all the following in the Match method bool contains = x.Contains(y); bool contains1 = x.IndexOf(y) != -1; bool contains2 = x.IndexOf(y, StringComparison.OrdinalIgnoreCase) != -1; bool contains3 = x.IndexOf(y, StringComparison.InvariantCultureIgnoreCase) != -1; bool contains4 = x.IndexOf(y, StringComparison.CurrentCultureIgnoreCase) != -1; but none return true for those values, when run in the rewrite module. But they do in the unit test. So something about the strings is clearly different any ideas?

    Read the article

  • C# string.Split() Matching Both Slashes?

    - by Sheep Slapper
    I've got a .NET 3.5 web application written in C# doing some URL rewriting that includes a file path, and I'm running into a problem. When I call string.Split('/') it matches both '/' and '\' characters. Is that... supposed to happen? I assumed that it would notice that the ASCII values were different and skip it, but it appears that I'm wrong. // url = 'someserver.com/user/token/files\subdir\file.jpg string[] buffer = url.Split('/'); The above code gives a string[] with 6 elements in it... which seems counter intuitive. Is there a way to force Split() to match ONLY the forward slash? Right now I'm lucky, since the offending slashes are at the end of the URL, I can just concatenate the rest of the elements in the string[], but it's a lot of work for what we're doing, and not a great solution to the underlying problem. Anyone run into this before? Have a simple answer? I appreciate it!

    Read the article

  • Enumerating a string

    - by JamesB
    I have a status which is stored as a string of a set length, either in a file or a database. I'm looking to enumerate the possible status' I have the following type to define the possible status' Type TStatus = (fsNormal = Ord('N'),fsEditedOnScreen = Ord('O'), fsMissing = Ord('M'),fsEstimated = Ord('E'),fsSuspect = Ord('s'), fsSuspectFromOnScreen = Ord('o'),fsSuspectMissing = Ord('m'), fsSuspectEstimated = Ord('e')); Firstly is this really a good idea? or should I have a seperate const array storing the char conversions? That would mean more than one place to update. Now convert a string to a status array I have the following, but how can I check if a char is valid without looping through the enumeration? Function StrToStatus(Value : String):TStatusArray; var i: Integer; begin if Trim(Value) = '' then begin SetLength(Result,0); Exit; end; SetLength(Result,Length(Value)); for i := 1 to Length(Value) do begin Result[i] := TStatus(Value[i]); // I don't think this line is safe. end; end; AFAIK this should be fine for converting back again. Function StatusToStr(Value : TStatusArray):String; var i: Integer; begin for i := 0 to Length(Value) - 1 do Result := Result + Chr(Ord(Value[i])) end; I'm using Delphi 2007

    Read the article

  • PHP functions wont work with String object, but works with it typed manually

    - by heldrida
    Hi, I'm trying to strip tags from a text output coming from an object. The problem is, that I can't. If I type it manually like "<p>http://www.mylink.com</p>", it works fine! When doing echo $item->text; it gives me the same string "<p>http://www.mylink.com</p>"; Doing var_dump or even gettype, gives me a string(). So, I'm sure its a string, but it's not acting like it, I tried several functions preg_replace, preg_match, strip_Tags, none worked. How can I solve this situation, how to debug it ? $search = array("<p>", "</p>"); $switch = array("foo", "baa"); //works just fine, when used $text = "<p>http://www.mylink.com</p>"; //it's a string for sure! var_dump($item->introtext); $text = $item->introtext; //doesn't work $text = str_replace($search, $switch, $text); $text = strip_tags($text, "<p>"); //doesn't work either. $matches = array(); $pattern = '/<p>(.*)<\/p>/'; preg_match($pattern, $text, $matches); //gives me the following output: <p>http://www.omeulink.com</p> echo $text;

    Read the article

  • replace a random word of a string with a random replacement

    - by tpickett
    I am developing a script that takes an article, searches the article for a "keyword" and then randomly replaces that keyword with an anchor link. I have the script working as it should, however I need to be able to have an array of "replacements" for the function to loop through and insert at the random location. So the first random position would get anchor link #1. The second random position would get anchor link #2. The third random position would get anchor link #3. etc... I found half of the answer to my question here: PHP replace a random word of a string public function replace_random ($str, $search, $replace, $n) { // Get all occurences of $search and their offsets within the string $count = preg_match_all('/\b'.preg_quote($search, '/').'\b/', $str, $matches, PREG_OFFSET_CAPTURE); // Get string length information so we can account for replacement strings that are of a different length to the search string $searchLen = strlen($search); $diff = strlen($replace) - $searchLen; $offset = 0; // Loop $n random matches and replace them, if $n < 1 || $n > $count, replace all matches $toReplace = ($n < 1 || $n > $count) ? array_keys($matches[0]) : (array) array_rand($matches[0], $n); foreach ($toReplace as $match) { $str = substr($str, 0, $matches[0][$match][1] + $offset).$replace.substr($str, $matches[0][$match][1] + $searchLen + $offset); $offset += $diff; } return $str; } So my question is, How can i alter this function to accept an array for the $replace variable?

    Read the article

  • Path String Combination Question.

    - by Nano HE
    Hi. Please see my code below. ifstream myLibFile ("libs//%s" , line); // Compile failed here ??? I want to combine the path string and open the related file again. #include <iostream> #include <fstream> #include <string> using namespace std; int main () { string line; ifstream myfile ("libs//Config.txt"); // There are several file names listed in the COnfig.txt file line by line. if (myfile.is_open()) { while (! myfile.eof() ) { getline (myfile,line); cout << line << endl; // Read details lib files based on the each line file name. string libFileLine; ifstream myLibFile ("libs//%s" , line); // Compile failed here ??? if (myLibFile.is_open()) { while (! myLibFile.eof() ) { print "success"; } myLibFile.close(); } } myfile.close(); } else cout << "Unable to open file"; return 0; }

    Read the article

  • Double null-terminated string

    - by wengseng
    I need to format a string to be double null-terminated string in order to use SHFileOperation. Interesting part is i found one of the following working, but not both: // Example 1 CString szDir(_T("D:\\Test")); szDir = szDir + _T('\0') + _T('\0'); // Example 2 CString szDir(_T("D:\\Test")); szDir = szDir + _T("\0\0"); //Delete folder SHFILEOPSTRUCT fileop; fileop.hwnd = NULL; // no status display fileop.wFunc = FO_DELETE; // delete operation fileop.pFrom = szDir; // source file name as double null terminated string fileop.pTo = NULL; // no destination needed fileop.fFlags = FOF_NOCONFIRMATION|FOF_SILENT; // do not prompt the user fileop.fAnyOperationsAborted = FALSE; fileop.lpszProgressTitle = NULL; fileop.hNameMappings = NULL; int ret = SHFileOperation(&fileop); Does anyone has idea on this? Is there other way to append double-terminated string?

    Read the article

  • Read whole ASCII file into C++ std::string

    - by Arrieta
    Hello, I need to read a whole file into memory and place it in a C++ std::string. If I were to read it into a char, the answer would be very simple: std::ifstream t; int lenght; t.open("file.txt", "r"); // open input file t.seekg(0, std::ios::end); // go to the end length = t.tellg(); // report location (this is the lenght) t.seekg(0, std::ios::beg); // go back to the beginning buffer = new char[length]; // allocate memory for a buffer of appropriate dimension t.read(buffer, length); // read the whole file into the buffer t.close(); // close file handle // ... do stuff with buffer here ... Now, I want to do the exact same thing, but using a std::string instead of a char. I want to avoid loops, i. e., I don't want to: std::ifstream t; t.open("file.txt", "r"); std::string buffer; std::string line; while(t){ std::getline(t, line); // ... append line to buffer and go on } t.close() any ideas?

    Read the article

  • Path String Concatenation Question.

    - by Nano HE
    Hi. Please see my code below. ifstream myLibFile ("libs//%s" , line); // Compile failed here ??? I want to combine the path string and open the related file again. #include <iostream> #include <fstream> #include <string> using namespace std; int main () { string line; ifstream myfile ("libs//Config.txt"); // There are several file names listed in the COnfig.txt file line by line. if (myfile.is_open()) { while (! myfile.eof() ) { getline (myfile,line); cout << line << endl; // Read details lib files based on the each line file name. string libFileLine; ifstream myLibFile ("libs//%s" , line); // Compile failed here ??? if (myLibFile.is_open()) { while (! myLibFile.eof() ) { cout<< "success\n"; } myLibFile.close(); } } myfile.close(); } else cout << "Unable to open file"; return 0; } Assume my [Config.txt] include the content below. And all the *.txt files located in libs folder. file1.txt file2.txt file3.txt

    Read the article

  • Javascript Regex: Testing string for intelligent query

    - by Shyam
    Hi, I have a string that holds user input. This string can contain various types of data, like: a six digit id a zipcode that contains out of 4 digits and two alphanumeric characters a name (characters only) As I am using this string to search through a database, the query type is determined on the type of search, which i want to handle serverside using JavaScript (yes, I am using JavaScript serverside). Searching on StackOverflow, brought me some interesting information, like the .test-method, which seems perfect for my needs. The test-method returns either true or false based on the evaluation on the string using a regex object. I am using this page as a reference: http://www.javascriptkit.com/jsref/regexp.shtml So I am trying to determine the zipcode, by using the following very noobish regex. var r = /[A-Za-z]{2,2}/ As far I can understand, this should limit the amount of occurrences of alphanumeric characters to a maximum of two. See beneath the output of my JavaScript console. > var r = /[A-Za-z]{2,2}/ > var x = "2233AL" > r.test(x) true > var x = "2233A" > r.test(x) false > var x = "2233ALL" > r.test(x) true /* i want this to be false */ > A little help would be really appreciated!

    Read the article

  • Passing a string to a function in C++

    - by Chef Flambe
    I want to pass a string like "Celcius" into a function that I have but I keep getting errors tossed back at me from the Function. System::Console::WriteLine' : none of the 19 overloads could convert all the argument types I figure I just have something simple wrong. Can someone point out my mistake please? Using MS Visual C++ 2010 I've posted the offending code. The other functions (not posted) work fine. void PrintResult( double result, std::string sType ); // Print result and string // to the console //============================================================================================= // start of main //============================================================================================= void main( void ) { ConsoleKeyInfo CFM; // Program Title and Description ProgramDescription(); // Menu Selection and calls to data retrieval/calculation/result Print CFM=ChooseFromMenu(); switch(CFM.KeyChar) // ************************************************************ { //* case '1' : PrintResult(F2C(GetTemperature()),"Celsius"); //* break; //* //* case '2' : PrintResult(C2F(GetTemperature()),"Fahrenheit"); //* break; //* //* default : Console::Write("\n\nSwitch : Case !!!FAILURE!!!"); //* } //************************************************************ system("pause"); return; } //Function void PrintResult( double result, std::string sType ) { Console::WriteLine("\n\nThe converted temperature is {0:F2} degrees {1}\n\n",result,sType); return; }

    Read the article

  • Sending arbitrarily long string over Java TCP socket

    - by bibismcbryde
    I have an Android app that communicates over a TCP socket with a server I wrote. The method I'm using now to read and write output works fine for smaller strings (up to 60kB) but I get an exception thrown when the string is much longer than that. Here is the relevant part of what I have for the server and client: Server: DataInputStream dis = null; DataOutputStream dos = null; try { dis = new DataInputStream(server.getInputStream()); dos = new DataOutputStream(server.getOutputStream()); String input = ""; input = dis.readUTF(); handle_input info = new handle_input(input, id); String xml = info.handle(); dos.writeUTF(xml); server.close(); } Client: Socket socket = null; DataOutputStream dos = null; DataInputStream dis = null; Boolean result; try { socket = new Socket(ip, port); dos = new DataOutputStream(socket.getOutputStream()); dis = new DataInputStream(socket.getInputStream()); dos.writeUTF(the_text); String in = ""; while (in.equals("")) { in += dis.readUTF(); } } How can I modify it to deal with potentially enormous Strings? I've been looking around and can't seem to find a clear answer. Thanks.

    Read the article

  • Unable to format 16Gb Usb Disk

    - by akshay.is.gr8
    Whenever i try to format my 16 GB usb disk using gparted it does to formating and when it refreshes then show unknown. tried disk utility as well. disk utility was able to format it into FAT but files vanish web the disk is removed and attached again. edit: the disk format completes every time but when using gparted it immediately show Unknown type file system and disk utility show FAT but when the Disk is unplugged and then connected the files are not there. either way it is unusable.

    Read the article

  • C# String.format extension method

    - by Paul Roe
    With the addtion of Extension methods to C# we've seen a lot of them crop up in our group. One debate revolves around extension methods like this one: public static class StringExt { /// <summary> /// Shortcut for string.Format. /// </summary> /// <param name="str"></param> /// <param name="args"></param> /// <returns></returns> public static string Format(this string str, params object[] args) { if (str == null) return null; return string.Format(str, args); } } Does this extension method break any programming best practices that you can name? Would you use it anyway, if not why? If I renamed the function to "F" but left the xml comments would that be epic fail or just a wonderful savings of keystrokes?

    Read the article

  • Ubuntu Unable to format 16Gb Usb Disk

    - by akshay.is.gr8
    Whenever i try to format my 16 GB usb disk using gparted it does to formating and when it refreshes then show unknown. tried disk utility as well. disk utility was able to format it into FAT but files vanish web the disk is removed and attached again. edit: the disk format completes every time but when using gparted it immediately show Unknown type file system and disk utility show FAT but when the Disk is unplugged and then connected the files are not there. either way it is unusable.

    Read the article

  • &quot;CLR Enabled&quot; is not required to use CLR built-ins

    - by AaronBertrand
    Books Online articles referencing built-in CLR functions (such as FORMAT() ) have a remark similar to the following: "FORMAT relies on the presence of .the .NET Framework Common Language Runtime (CLR)." A lot of people seem to interpret this as meaning: "You must enable the sp_configure option 'CLR enabled' in order to use FORMAT()." Some then go on and suggest you run code similar to the following before you play with these functions: EXEC sp_configure 'show advanced options' , 1 ; GO RECONFIGURE...(read more)

    Read the article

  • Having trouble's understanding NIF model file format?

    - by NoobScratcher
    I'm attempting too develop a 3rd party application to make it easy to import 3d model part's into my mod for skyrim the plan was to have a fileviewer and preview window of the nif model but since , I don't know what the NIF file format actually is or where to get the vertex data from it or the hole nine yards of parsing a text file in detail I'm at a lost what to do. I'm very good at C++ but not at this super over complicated file formats , id much prefer .obj over the nif file format specification here -- http://niftools.sourceforge.net/doc/nif/index.html If someone could help me in understanding the file format in a natural and simple way and the exact parsing needed to create the 3D Model in the frustum and a explanation on how you figured that out would be happy to know. I use cygwin , notepad++ , win32 7

    Read the article

  • Usb boot device totally unable to be formatted

    - by fuqda
    I'm really upset by now, I've been trying 2hours straight to format a stupid usb drive (I'm new to ubuntu and I dont know if I will last long at this rate) Basically this was the lubuntu boot usb key I tried to remove files with sudo rm I tried to format disk with disk utility I tried to format disk with gparted (with unmounting beforehand) NOTHING WORKS. I cant delete a file. I cant move a file to the usb key. I cant do anything. This is really infuriating.. I dont know what to do ? here are some gparted errors while trying to format to fat32 after unmounting error fsyncing/closing/dev/sdb: input/output error input/output error during write on /dev/sdb when I try to remove by hand, it says "read-only file"

    Read the article

  • Setting collation property in the connection string to SQL Server 2005

    - by user369745
    I have a ASP.Net web application with connection string for SQL Server 2005 in the web.config. Data Source=ABCSERVER;Network Library=DBMSSOCN;Initial Catalog=myDataBase; User ID=myUsername;Password=myPassword; I want to specify the collation property in the web.config for different languages like French like Data Source=ABCSERVER;Network Library=DBMSSOCN;Initial Catalog=myDataBase; User ID=myUsername;Password=myPassword;Collation=French_CS_AS But the Collation word is not valid in the connection string. What is the correct keyword that we need to use to specify the collation in SQL Server 2005 connection string?

    Read the article

  • Additional spaces in String having read text file to String using FileInputStream

    - by David
    Hi, I'm trying to read in a text file to a String variable. The text file has multiple lines. Having printed the String to test the "read-in" code, there is an additional space between every character. As I am using the String to generate character bigrams, the spaces are making the sample text useless. The code is try{ FileInputStream fstream = new FileInputStream(textfile); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); //Read corpus file line-by-line, concatenating each line to the String "corpus" while ((strLine = br.readLine()) != null) { corpus = (corpus.concat(strLine)); } in.close(); //Close the input stream } catch (Exception e) {//Catch exception if any System.err.println("Error test check: " + e.getMessage()); } I'd be grateful for any advice. Thanks.

    Read the article

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