w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
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

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

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

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++

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++

split array of char with delimiter '#' and save in another array
My first guess is that you're reading off the end of the input data. Note that read does not nul-terminate the string, so your printf statement is immediately broken. Try this: int read_vkluci = read(sock_descriptor, read_from_server, sizeof(read_from_server)-1); and this read_from_server[read_vkluci] = ''; printf("naredbi=%s ", read_from_server); BTW, sizeof(read_from_server) will only work correctly if read_from_server is an array type. If it's a pointer to a buffer then that's broken too.

Categories : C

MD4 hash with openssl, save result into char array
Firstly, your call to MD4() provides an incorrect address for the string and digest arrays: by using &, you are getting the array's address (char **), not the address of the first character. Since you are explicitly casting &string and &digest to unsigned char*, the compiler won't warn you. Remove the casts, and you will receive this warning: warning: passing argument 1 of 'MD4' from incompatible pointer type So instead call MD4() this way: MD4(string, strlen(string), digest); I personally prefer to avoid explicitly casting pointers unless it is really necessary, that way you will catch incorrect type casting much more easily. Next, you attempt to use sprintf() to convert digest to a hexadecimal integer: sprintf(test, "%02x", (unsigned int)digest);. Two things wrong here:

Categories : C

How to get current date and time and save it into char* array in proper format?
You can use strftime function: http://www.gnu.org/software/libc/manual/html_node/Formatting-Calendar-Time.html strftime is described in C99 Standard in 7.23.3.5.

Categories : C

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#

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

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

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++

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++

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++

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

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++

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

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++

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

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#

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++

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++

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#

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++

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

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++

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++

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++

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

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++

how to save a blob and a string in the same array in php
The query you are executing is probably not returning any rows. Try this: if (false !== ($query = mysql_query("SELECT * FROM data WHERE index ='1'")) { $data = mysql_fetch_array($query); echo $data['title']; }

Categories : PHP

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

What to call method which returns char* ( String in Java and char* in C++)?
It returns a String object and you can use the JNI string functions to convert that string to a char*: char* gPGGetName() { jobject objStr = env->CallObjectMethod(g_Obj, g_s3eGPGGetName); jsize len = env->GetStringUTFLength(objStr); const char* strPtr = env->GetStringUTFChars(objStr, 0); char* buffer = (char*)malloc((len + 1) * sizeof(char)); memcpy(buffer, strPtr, len); buffer[len] = ''; env->ReleaseStringUTFChars(objStr, strPtr); return buffer; }

Categories : Android

How compare a char / single char string - with some list of alphabets set
If the starting letter is always an English character (or anything representable by a reasonably small integer that fits into an unsigned char), then here's a solution (the fastest possible one I can think of - uses no jumps except for the first check for initialization and only plain old integers are used instead of the somewhat heavier-weight comparison of NSString instances): - (UIColor *)colorFromName:(NSString *)name { static UIColor *strs[1 << CHAR_BIT] = { nil }; static BOOL initted = NO; if (!initted) { strs['a'] = [UIColor greyColor]; strs['b'] = [UIColor whiteColor]; // ... strs['z'] = [UIColor blueColor]; initted = YES; } unsigned char first = tolower([name characterAtIndex:0]); return strs[first]; }

Categories : IOS

Unable to pass an address of array of type char *[2] to function taking char ***
char *array[2] = {"string", "value"}; is an array with 2 elements of char *. Using array as an address results to a pointer to the first element, i. e. of type char **. Using &array results to a pointer to the same place, but of type char *(*)[2] (not sure if the spelling is right). This is not the same as a char *** - the representation in memory is completely different. To be more verbose, +++++++++++++++++++++++ + array[0] + array[1] + +++++++++++++++++++++++ this is the array. char ** p1 = array; // is a pointer to the first element, which in turn is a pointer. char *(*p2)[2] = &array; // is a pointer to the whole array. Same address, but different type, i. e. sizeof(*p1) != sizeof(*p2) and other differences. char ***p3 = &p1; // Now, p1 is a different pointer va

Categories : C

Entity Framework 5 do not save array string
Instead of using an array of strings, you can alternatively use a simple string column with some kind of separator like ';' or '|', anything will do. Just make sure that when you retrieve your data from the database you call the C# String.Split method, passing to it the same separator as parameter. For example: string stringToBePersisted = "First Value|Second Value|Third Value"; string[] stringsRetrieved = columnValue.Split('|');

Categories : C#

How to properly copy char array to char array?
You're correct that you need to allocate memory in the second option. filenames[i] = strdup(filename_inzip); is the easiest way of doing this. strdup is a Posix function rather than standard C. If it isn't available for you filenames[i] = malloc(strlen(filename_inzip)+1); if (filenames[i] != NULL) { strcpy(filenames[i], filename_inzip); } does an equivalent job Note that you'll also have to call free for each array element you allocate later in your program.

Categories : C



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