w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
How is a string literal equal to char*, and how should I take a string as a parameter
surely it is a pointer to a single char, not an array of chars It's a pointer to the first character of an array of char. One can access each element of the array using a pointer to its first element by performing pointer arithmetic and "array" indexing. What datatype should the parameter be? const char *, if you don't wish to modify the characters from within the function (this is the general case), and char * if you do.

Categories : C

C - Sort char string in array to equal char user input
OK, so basically you want to convert a sorted array of letters to a specific (random?) ordering and record the swaps along the way, right? Here is one way to do this. #define SWAP(a,b) a^=b;b^=a;a^=b int main(int argc, char* argv[]) { char* wordInput=argv[1]; char* newWord = (char*)malloc((strlen(wordInput) + 1) * (sizeof(char))); int i,j,k; fprintf(stdout, "Word is %s ", wordInput); // Sort wordInput into newWord. for (i=0; i<strlen(wordInput); i++) { // Put this one at the end. newWord[i]=wordInput[i]; // Start at the back of the string, and move it forward if it is less. for (j=i-1; j>=0; j--) { if (newWord[j+1] < newWord[j]) { SWAP(newWord[j+1], newWord[j]); } else { break; } } } newWord[strlen(wordInput)]

Categories : C

How to duplicate string token to char */char array
Call c_str on the string: word[i] = (const char *)strdup(t.c_str()); For reference: http://en.cppreference.com/w/cpp/string/basic_string/c_str

Categories : C++

Adding string, char by char, into a 2dim array
Why does it know to do this? Because in C and C++, elements of an array are laid out contiguously in memory. Multidimensional arrays are simply arrays of arrays, and so are also contiguous. So when you write past the first row of your array, it simply keeps writing into memory and happens to get to the next row, since that next row is next up in the memory. What you can do is the following, if you want to do bounds checking: const int ROW = 5; const int COL = 5; char arr[ROW][COL] = {0}; for (int i = 0; i < new_keyword.length() && i < ROW * COL; i++) (&arr[0][0])[i] = new_keyword[i]; for (int i = 0; i < new_alphabet.length() && i + new_keyword.length() < ROW * COL; i++) (&arr[0][0])[new_keyword.length() + i] = new_alphabet[i]; Or, as Hello

Categories : C++

C - Comparing string literal with character array
I think this is a perfect starting point for you: http://www.wikihow.com/Compare-Two-Strings-in-C-Programming It's probably written at the right level for you. Good luck and welcome to stackoverflow!

Categories : C

JavaScript string literal in object literal syntax error
You have an unclosed string literal. JavaScript strings are not multi line by default. var modalcontent = { description1 : '<div id = "description"><div class = "tbc"> '+ '<label class = "tbc" for = "tbc">Description</label>'+ '</div>'+ '<div class = "tbc">'+ '<input type = "text" class = "tbc" name = "description" id = "tbc" placeholder = "Enter description">'+ '</div>'+ '</div>'+ '<!--end description div-->' } (fiddle) Alternatively, you can create multi line string by using the character, those only work in newer implementations. See this related question or the language specification. Note: It's usually not the best idea to store HTML in strings, it makes it harder to debug and work with. You can usually

Categories : Javascript

How to append regex literal with string literal in javascript
Don't use a literal. Use the RegExp constructor : var reg = new RegExp("(\d+\s" + query + ")");

Categories : Javascript

Parse a large string literal in JS with regex into object array
Description This regex will parse the text into a roman numeral and body. The body can then be split on the new line . ^s+([CDMLXVI]{1,12})(?: | |$).*?(?:^.*?)(^.*?)(?=^s+([MLXVI]{1,12})(?: | |$)|) Capture Groups Group 0 get the entire matching section gets the roman numeral gets the body of the section, not including the roman numeral Javascript Code Example: Sample text pulled from your link VII Lo! in the orient when the gracious light Lifts up his burning head, each under eye Doth homage to his new-appearing sight, VIII Music to hear, why hear'st thou music sadly? Sweets with sweets war not, joy delights in joy: Why lov'st thou that which thou receiv'st not gladly, Or else receiv'st with pleasure thine annoy? IX Is it for fear to wet a wid

Categories : Javascript

How to select rows from character array that match char string and save them in a new array?
Try ismember(A(:, 1:numel(B)), B, 'rows') rather to get a logical vector that indexes only the rows you want and now A(C,:) to extract the rows The reason you're getting a dimension mismatch error is because your A(:,1:9) has many rows but B only has one and Matlab does not automatically broadcast like Octave or Python. You could do it using either repmat or bsxfun but in this case ismember is the correct function to choose.

Categories : Matlab

Passing C# structure with string array to c++ function which accepts void * for c# structure and char** for c# string array
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] public String[] Parameters; is an inline array. The C++ declaration that matches is: char* Parameters[2]; But you are trying to match it to: char** Parameters; and that's completely different. You will need to marshal this by hand. In the C# struct declare Parameters to be IntPtr. Then allocate native memory with Marshal.AllocHGlobal to hold an array of pointers. And then populate those pointers with pointers to your strings. [StructLayout(LayoutKind.Sequential)] public struct TestInfo { public int TestId; public IntPtr Parameters; } static void Main(string[] args) // no need for unsafe { TestInfo testInfo; testInfo.TestId = 1; testInfo.Parameters = Marshal.AllocHGlobal(2*Marshal.SizeOf(typeof(IntPtr)));

Categories : C#

java string split into array, how to save into the same array the char im splitting with?
How about splitting before or after each of X + - / characters? BTW you don't have to escape + and / in character class ([...]) String[] tmp = strEquation.split("(?=[X+\-/])|(?<=[X+\-/])"); seems to do the trick.

Categories : Java

Why is there no empty char literal?
A char by definition has a length of one character. Empty simply doesn't fit the bill. Don't run into confusion between a char and a string of max length 1. They sure look similar, but are very different beasts.

Categories : C#

How to convert literal char hex value into the hex value itself?
For each character c, the value is: if ('0' <= c && c <= '9') return c - '0'; if ('a' <= c && c <= 'f') return c - 'a' + 10; if ('A' <= c && c <= 'F') return c - 'A' + 10; // else error, invalid digit character Now just iterate over the string from left to right, adding up the digit values, and multiplying the result by 16 each time. (This is implemented for you by the standard library in the strto*l functions with base 16.)

Categories : C

copying portions of string, which are stored in a char array, to another array
You are copying pointers to statically declared strings to an array. That's theoretically fine. Howevery, you want to cut off the remainder of the strings, so you need to prepare memory for the target strings, because if you write to the strings you will invoke undefined behaviour. This line: array_main[i] = ("%*.*s ",1,3,array1[i]); definitely doesn't do what you want though. I think this shouldn't even compile. You loop over the array and malloc the appropriate size of bytes (3+1), then copy over the parts of the string that you want (don't forget the 0-byte at the end). So it should look like this: for(i = 0; i < 6; i++) { array_main[i] = malloc(4); snprintf(array_main[i], 4, "%.3s", array[i]); printf("%s ", array_main[i]); free(array_main[i]); } A simpler ve

Categories : C

Using strcmp to compare a char pointer and a literal
You need to pass a char* to strcmp, like args. Here is the prototype for strcmp from here: int strcmp ( const char * str1, const char * str2 ); So since args is a char* and "r" will give you a char* you should try: /* since you're learning, print out what this thing does */ #include <stdio.h> printf("Output: %d ",strcmp(args,"r"));

Categories : C

Transform char array into String
If you have the char array null terminated, you can assign the char array to the string: char[] chArray = "some characters"; String str(chArray); As for your loop code, it looks right, but I will try on my controller to see if I get the same problem.

Categories : String

C++ string to char* array struct
RequestInfo[1] = "1"; is not doing what you think. It's either RequestInfo[1].string = "1"; if RequestInfo is a vector of MqlStr objects containing at least 2 elements, or RequestInfo->string = "1"; if RequestInfo is a pointer to a single MqlStr object.

Categories : C++

How to convert char* array into std::string
Try a loop: std::string ss; for (int i=0; i < 50; i++) ss += std::string(excluded_string[i]) + " "; You're code in the best situation will put first string in ss.

Categories : C++

Assign string to column of char array
I strongly advice against raw multi-dimensional arrays in C++ - they're error prone and inflexible. Consider Boost MultiArray. That said, you could always "hide" the complexity by writing a helper function. Here's a fairly generic version that works with 2-dimensional arrays of any size/element type: template<typename T, size_t N, size_t M> void setColumn(T(&arr)[N][M], size_t col, std::string const& val) { assert(col>=0 && col <M); for (auto& row : arr) row[col] = val; } Note how it takes the array by reference, so template argument deduction can be used to "sense" the dimension bounds (N, M) it asserts that the column index is actually valid (bonus feature) it uses range-based for, which is actually pretty concise, and certainly

Categories : C++

C- to check if a char in a string belongs in an array
Code seems to be working for me. I did edit the code in the question, I may have unintentionally removed the problem. Please feel free to re-edit and post the original code, I can't seem to rollback my edit. Working: #include <stdio.h> #include <stdlib.h> #include <string.h> int main(){ char array[] = { 'a', 'b', 'c', 'd', 'e' }; char input[40]; /*Reserved for the string*/ int lengthofstring,i; scanf("%[^ ]s",input); /*This enables spaces in the input, and let's say the string in this case is "example"*/ lengthofstring=strlen(input); for (i=0;i<lengthofstring;i++){ if (memchr(array,input[i],sizeof(array))) { /* Now in this example input[i]="e", when i=0 and sizeof(array)=5*/ printf("The letter %c does exis

Categories : C

How can I convert a string to a char array in ActionScript 3?
I am not sure if this helps your purpose but you can use String#split(): If you use an empty string ("") as a delimiter, each character in the string is placed as an element in the array. var array:Array = "split".split(""); Now you can get individual elements using index array[0] == 's' ; array[1] == 'p' ....

Categories : Actionscript

Convert a string in char to array in MATLAB
Assuming you have a char array (not a cellstring): s = ['gvs( 0.000000000000000e+000, 1.601985139535780e+002)' 'gvs(-5.000000000000000e-005, 1.365231866954370e+002)' 'gvs(-1.000000000000000e-004, 1.169431404340180e+002)' 'gvs(-5.000000000000000e-004, 3.187711314514890e+001)' 'gvs(-2.000000000000000e-004, 8.589930648472340e+001)'] Then you can simply textscan(): data = textscan(s','gvs(%f%f)','CollectOutput',1,'Delimiter',','); data = data{1} data = 0 160.1985 -0.0001 136.5232 -0.0001 116.9431 -0.0005 31.8771 -0.0002 85.8993 If s is a cellstring, then before calling textscan, convert to char(): s = char(s);

Categories : Arrays

C++ creating a string from char array elements?
You can cast chars to ints and vice versa because they are basic language types. Strings are implemented as a class so you need to invoke the string constructor for both chars then concatenation the two resulting strings into mystring

Categories : C++

How to make char array and std::string "in a relationship"?
class Observable_CharArray { char* arr; std::function<void(char*)> change_callback; public: Observable_CharArray(int size, std::function<void(char*)> callback) : arr(new char[size]), change_callback(callback){} ~Observable_CharArray()/*as mentioned by Hulk*/ { delete[] arr; } void SetCallback(std::function<void(char*)> callback) { change_callback = callback; } /*other member function to give access to array*/ void change_function() { //change the array here change_callback(arr); } }; class Observer_String { std::string rep; void callback(char* cc) {

Categories : C++

C++ how to convert string to char array and check for digits?
Simple, just iterate through the std::string as such: std::string dblNumOne; std::cin >> dblNumOne; for(unsigned int i = 0; i < dblNumOne.length(); i++) { if (isalpha(dblNumOne[i])) { printf ("character %c is alphabetic ", dblNumOne[i]); } else { printf ("character %c is not alphabetic ", dblNumOne[i]); } }

Categories : C++

Invalid length for a Base-64 char array or string. AES in C#
You are trying to pull the IV out of the string you will be encrypting. Try changing: rm.IV = Convert.FromBase64String(ASCIIEncoding.UTF8.GetString(Convert.FromBase64String(text)).Split(',')[0]); to: rm.IV = Convert.FromBase64String(ASCIIEncoding.UTF8.GetString(Convert.FromBase64String(key)).Split(',')[0]);

Categories : C#

converting a string to byte (unsigned char) array cpp
If at all possible, I'd advise using a std::vector<unsigned char> instead of an actual array. Using that, I guess I'd do something like this: std::istringstream buffer(msg); std::vector<unsigned char> bbuffer; unsigned int ch; while (buffer >> std::hex >> ch) bbuffer.push_back(ch); If you really insist on the array, you could do something like: std::istringstream buffer(msg); char bbuffer[12]; unsigned int ch; for (int i=0; buffer >> std::hex >> ch; i++) bbuffer[i] = ch & 0xff; But the vector is usually preferable.

Categories : C++

CLR: Convert a (C#) string into a null-terminated array of char (C)?
If you're passing it into a C function using P/Invoke, I believe the marshaller will just do it for you, based on attributes applied to the parameter in the declaration. So based on this documentation, you probably want something like: [DllImport("YourLibrary.Dll")] public extern void Foo([UnmanagedType.LPStr] string text)

Categories : C#

c++ Pass quoted string as char array to a function
I believe your problem has to do with using unsigned chars, when I put it into my code it complains on compile about it. It may have something to do with unsigned char not being able to use escape characters like , but I can't be sure. IntelliSense: argument of type "const char *" is incompatible with parameter of type "unsigned char *" Is the compile error I get. When I changed it to just being a regular char * as the parameters, it worked fine.

Categories : C++

NullReference Exception in converting string to Char array
The read should be null when the loop is finished and calling ToCharArray on null should give exception. you can put this statement in while loop. I believe you are trying to do some experimentation as you have already printed the string with Console.WriteLine(read); while ((read = sr.ReadLine()) != null) { Console.WriteLine(read); char[] myChar = read.ToCharArray(); for (int i = 0; i < myChar.Length; i++) Console.WriteLine(myChar[i]); }

Categories : C#

Altering start position and insterting string into char array
No. Arrays don't have methods to insert things into them. STL containers have such methods. This is one of the many reasons why they are preferred to raw arrays. If you still need to work with raw array for some reason, you can write a function which does what you need, using additional variable to perform the copy in it. But the returned result will be a different array, not your original one.

Categories : C++

Function to find and replace string in char array (streams) c++
You need two for loops, one inside the other. The outer for loop goes through the Memory string one character at a time. The inner loop starts looking for the FindWord at the position you've got to in the outer loop. This is a classic case where you need to break the problem down into smaller steps. What you are trying is probably a bit too complex for you to do in one go. Try the following strategy 1) Write some code to find a string at a given position in another string, this will be the inner loop. 2) Put the code in step 1 in another loop (the outer loop) that goes through each position in the string you are searching in. 3) Now you can find all occurrences of one string in another, add the replace logic.

Categories : C++

Weird behaviour when searching for char in array string elements
You're adding new elements to $strstr, $strpos tables and so on and in the end you do for... and printing from these tables where $k keys don't necessarily have to exists. Check var_dump or print_r on these tables and you will see that in fact they got elements, but their indexes aren't matched with $array indexes (and i guess that's what you want to achieve). You can change foreach ($array as $key) to foreach ($array as $index => $key) and all occurences like $strstr[] = "found"; to $strstr[$index] = "found"; (also for other recognision methods) and then run the script again to see results. In last block (for($k = 0; $k < $arraysize; $k++)...) you should either validate if $strstr[$k] (and other arrays) exists before printing it, or print these arrays separately by foreach. You

Categories : PHP

How to copy a char array / String a variable number of times C++
A simple loop would do. If you are concerned about re-allocations, you can call std::string::reserve on the copy string: #include <string> #include <iostream> int main() { const int num + 5; std::string s = "copyme"; std::string b; b.reserve(s.size() * num); // reserve space for num* "copyme" for (int i = 0; i < num; ++i) b += s; std::cout << b << std::endl; }

Categories : C++

Extracting parts of string and place parts into a char array and another string variable C++
If your input is space-delimited, you can read the studentID into a string (ex: cin >> studentID). You can then write a loop to read 20 characters (char datatype) into your testAnswers array.

Categories : C++

char Array to string conversion results in strange characters - sockets
If you're reading in a zero-terminated string from your socket, there's no need for a conversion, it's already a char string. If it's not zero-terminated already, you'll need some other kind of terminator because sockets are streams (assuming this is TCP). In other words, you don't need my_string = std::string(my_stream);

Categories : C++

Reading white spaces from a text file into Char/String array
String's toCharArray() will likely solve your problem. Call it on each line read and feed it into each row of your array of char[][]. // in constants declaration public final static int ROWS = 2; public final static int COLS = 10; // somewhere else in your code. char[][] chars = new char[ROWS][COLS]; // making sure to catch exceptions with opening and reading file BufferedReader br = new BufferedReader(new FileReader("files/myFile.txt")); for(int i = 0; i < ROWS; ++i) { String line = br.readLine(); // check line exists, has a length of COLS, else throw exception. chars[i] = line.toCharArray(); } ROWS and COLS are program constants, and you'd better make darn sure that these numbers are correct, else this code will go down in flames. Better to use List<List<Character&

Categories : Java

Fast C++ I/O to read a string (char array) into a vector, plus resolving error
You are just storing the pointer to the buffer used to read... all the pointers will point to the same buffer and this is why you see the last string repeated. Just use an std::vector<std::string> instead.

Categories : C++

How to have a verbatim string literal inside a verbatim string literal?
string mystring = "CMD.AddParameters("@Pkey", SqlDbType.Int, Pkey.ToString());"; or string mystring = @"CMD.AddParameters(""@Pkey"", SqlDbType.Int, Pkey.ToString());";

Categories : C#

How can I write a function boolean succeeds(char a, char b, String s)? using s.equals(""), s.charAt(0), s.substring(1)
Something like this should work. I have not compiled this. Hopefully it gets you in the right direction, even with possible syntax errors. public boolean succeeds(char a, char b, String s){ boolean sawFirst= false; for(int i=0;i<s.length();i++){ if(!sawA){ if(s.charAt(i)==b) sawFirst = true; } else{ if(s.charAt(i)!=a) return false; else sawFirst= false; } } return true; }

Categories : Java



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.