c,arrays,char,words , How do would I alphabetize the strings in my character array?


How do would I alphabetize the strings in my character array?

Question:

Tag: c,arrays,char,words

I've written a program to count the occurrences of letters and words from a string that the user enters. I have successfully gotten most of it to work now, however, I must also alphabetize the words I have stored in my array of pointers. I saw a function void sortstring() that was supposed to to just this but it doesn't seem to work at all. How would I go about it?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


void findLetters(char *ptr);
void findWords(char *point);
void sort_string(char *p);

int main()
{
    char textStream[100]; //up to 98 characters and '\n\ and '\0'

    printf("enter some text\n");
    if (fgets(textStream, sizeof (textStream), stdin)) //input up to 99 characters
    {
        findLetters(textStream);
        findWords(textStream);
        sort_string(textStream);
    }
    else
    {
        printf("fgets failed\n");
    }

    return 0;
}

void findLetters(char *ptr) //find occurences of all letters
{
    int upLetters[26];
    int loLetters[26];
    int i;
    int index;

    for (i = 0; i < 26; i++) // set array to all zero
    {
        upLetters[i] = 0;
        loLetters[i] = 0;
    }
    i = 0;
    while (ptr[i] != '\0') // loop until prt[i] is '\0'
    {
        if (ptr[i] >= 'A' && ptr[i] <= 'Z') //stores occurrences of uppercase letters
        {
            index = ptr[i] - 'A';// subtract 'A' to get index 0-25
            upLetters[index]++;//add one
        }

        if (ptr[i] >= 'a' && ptr[i] <= 'z') //stores occurrences of lowercase letters
        {
            index = ptr[i] - 'a';//subtract 'a' to get index 0-25
            loLetters[index]++;//add one
        }
        i++;//next character in ptr
    }
    printf("Number of Occurrences of Uppercase letters\n\n");
    for (i = 0; i < 26; i++)//loop through 0 to 25
    {
        if (upLetters[i] > 0)
        {
            printf("%c : \t%d\n", (char)(i + 'A'), upLetters[i]);
            // add 'A' to go from an index back to a character
        }
    }
    printf("\n");
    printf("Number of Occurrences of Lowercase letters\n\n");
    for (i = 0; i < 26; i++)
    {
        if (loLetters[i] > 0)
        {
            printf("%c : \t%d\n", (char)(i + 'a'), loLetters[i]);
            // add 'a' to go back from an index to a character
        }
    }
    printf("\n");
}

void findWords(char *point)
{
    int i = 0;
    int k = 0;
    int count = 0;
    int j = 0;
    int space = 0;
    int c = 0;
    int len = strlen(point);
    char copy[50][100];
    char* delim = "{ } . , ( ) ";
    char **word;
    char *newpoint;
    char *newerpoint;
    char *token;
    int occur[50]; // will store number of occurances of each word

    for (; i < 50; i++) //sets all indexes to 0
    {
        occur[i] = 0;
    }

    for (i = 0; i < len; i++) //counts # of spaces between words
    {
        if ((point[i] == ' ') || (point[i] == ',') || (point[i] == '.'))
        {
            space++;
        }
    }
    word = malloc(sizeof(char*)*(space+1)); //allocates memory to array according to number of words
    newpoint = malloc(strlen(point)+1);
    strcpy(newpoint, point);
    newerpoint = malloc(strlen(point) + 1);
    strcpy(newerpoint, point);
    token = strtok(newpoint, delim);

    for (k; k <= space && token != NULL; k++)
    {
        word[k] = malloc(strlen(token) + 1);
        strcpy(word[k], token);
        token = strtok(NULL, delim);
        printf("%s\n", word[k]);
    }

    for (k = 0; k <= space; k++)
    {
        free(word[k]);
    }
}

void sort_string(char *p)
    {
        int c, d = 0, length;
        char *pointer, *result, ch;

        length = strlen(p);
        result = (char*)malloc(length + 1);

        pointer = p;

        for (ch = 'a'; ch <= 'z'; ch++)
        {
            for (c = 0; c < length; c++)
            {
                if (pointer == ch)
                {
                    *(result + d) = *pointer;
                    d++;
                }
                pointer++;
            }
            pointer = p;
        }
        *(result + d) = '\0';

        strcpy(p, result);
        free(result);
    }

EDITED VERSION:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void findLetters(char *ptr);
void findWords(char *point);
int compare_str (const void *a, const void *b);


int main (void)
{
    char textStream[100] = {0};     //up to 98 characters and '\n\ and '\0'
    typedef unsigned int size_t;
    size_t len = 0;
    printf ("enter some text\n");
    if (fgets (textStream, sizeof textStream, stdin)) //input up to 99 characters
    {
        len = strlen (textStream);
        textStream[--len] = 0;      // strip newline from end of textStream

        findLetters (textStream);
        findWords (textStream);
    }
    else
    {
        printf("fgets failed\n");
    }

    return 0;
}

void findLetters(char *ptr) //find occurences of all letters
{
    int upLetters[26];
    int loLetters[26];
    int i;
    int index;

    for (i = 0; i < 26; i++) // set array to all zero
    {
        upLetters[i] = 0;
        loLetters[i] = 0;
    }
    i = 0;
    while (ptr[i] != '\0') // loop until prt[i] is '\0'
    {
        if (ptr[i] >= 'A' && ptr[i] <= 'Z') //stores occurrences of uppercase letters
        {
            index = ptr[i] - 'A';// subtract 'A' to get index 0-25
            upLetters[index]++;//add one
        }

        if (ptr[i] >= 'a' && ptr[i] <= 'z') //stores occurrences of lowercase letters
        {
            index = ptr[i] - 'a';//subtract 'a' to get index 0-25
            loLetters[index]++;//add one
        }
        i++;//next character in ptr
    }
    printf("Number of Occurrences of Uppercase letters\n\n");
    for (i = 0; i < 26; i++)//loop through 0 to 25
    {
        if (upLetters[i] > 0)
        {
            printf("%c : \t%d\n", (char)(i + 'A'), upLetters[i]);
            // add 'A' to go from an index back to a character
        }
    }
    printf("\n");
    printf("Number of Occurrences of Lowercase letters\n\n");
    for (i = 0; i < 26; i++)
    {
        if (loLetters[i] > 0)
        {
            printf("%c : \t%d\n", (char)(i + 'a'), loLetters[i]);
            // add 'a' to go back from an index to a character
        }
    }
    printf("\n");
}

void findWords(char *point)
{
    int i, k, count, space;
    int len = strlen (point);
    char *delim = "\n { } . , ( ) ";
    char **word = NULL;
    char *newpoint = NULL;
    char *token = NULL;

    i = k = count = space = 0;

    for (i = 0; i < len; i++) //counts # of spaces between words
        if ((point[i] == ' ') || (point[i] == ',') || (point[i] == '.'))
            space++;

    word = malloc (sizeof *word * space + 1); //allocates memory to array according to number of words
    newpoint = malloc (strlen (point) + 1);
    strcpy (newpoint, point);
    token = strtok (newpoint, delim);

    printf ("\nSeparating and saving words in pointer array:\n\n");
    for (k = 0; token != NULL; k++)
    {
        word[k] = malloc (strlen (token) + 1);
        strcpy (word[k], token);
        token = strtok (NULL, delim);
        printf ("%s\n", word[k]);
    }

    count = k;  /* save number of string in word */

    qsort (word, count, sizeof *word, compare_str);     /* sort the array of pointers */

    printf ("\nSorted words in pointer array:\n\n");
    for (k = 0; k < count; k++)
        printf ("%s\n", word[k]);

    for (k = 0; k < count; k++)
    {
        free(word[k]);
    }
}


int compare_str (const void *a, const void *b)
{
    const char **ia = (const char **)a;
    const char **ib = (const char **)b;
    return strcmp(*ia, *ib);
}

Answer:

When you do get it working, I think you are in for a surprise. The sort_string function has nothing whatsoever to do with sorting words in an array of pointers instead, it sorts characters in an array. For example:

$ ./bin/str_sort_words

Enter a string: a quick brown fox jumps over the lazy dog
  sorted words: aabcdeefghijklmnoooopqrrstuuvwxyz

Instead you need to sort the array of pointers with qsort so that you are actually sorting words instead of characters. To use qsort you must provide it a compare function so that it knows the size and number of items to sort. For an array of pointers, a qsort compare function looks like this:

/* qsort C-string comparison function */
int compare_str (const void *a, const void *b)
{
    const char **ia = (const char **)a;
    const char **ib = (const char **)b;
    return strcmp(*ia, *ib);
}

Then in your case, you must call it in the findWords function where the pointer array word lives as follows:

qsort (word, count, sizeof *word, compare_str);

(where count is your space + 1 equivalent). Now before we look at the answer, you need to enable Warnings when you compile (which your code doesn't due to the pointer/int mismatch in if (pointer == ch) which should be if (*pointer == ch).

But beyond that, compiling with warnings enabled would have pointed out a whole list of problems in findWords. To enable warnings add -Wall -Wextra to your compile string.

Now let's look at changes to your code. Always initialize All variables:

char textStream[100] = {0};     //up to 98 characters and '\n\ and '\0'
size_t len = 0;

Next, when using fgets or getline, it is a good idea to strip the tailing newline so it isn't dangling off your strings:

if (fgets (textStream, sizeof textStream, stdin)) //input up to 99 characters
{
    len = strlen (textStream);
    textStream[--len] = 0;      // strip newline from end of textStream
    ...

Now, changes to findWords:

void findWords(char *point)
{
    int i = 0;
    int k = 0;
    int count = 0;
    // int j = 0;
    int space = 0;
    // int c = 0;
    int len = strlen(point);
    // char copy[50][100];
    char* delim = "{ } . , ( ) ";
    char **word = NULL;
    char *newpoint = NULL;
    char *newerpoint = NULL;
    char *token = NULL;
//     int occur[50]; // will store number of occurances of each word
// 
//     for (; i < 50; i++) //sets all indexes to 0
//     {
//         occur[i] = 0;
//     }


    for (i = 0; i < len; i++) //counts # of spaces between words
    {
        if ((point[i] == ' ') || (point[i] == ',') || (point[i] == '.'))
        {
            space++;
        }
    }
    word = malloc (sizeof *word * space + 1); //allocates memory to array according to number of words
    newpoint = malloc (strlen (point) + 1);
    strcpy (newpoint, point);
    newerpoint = malloc (strlen (point) + 1);
    strcpy (newerpoint, point);
    token = strtok (newpoint, delim);

    printf ("\nSeparating and saving words in pointer array:\n\n");
    for (k = 0; token != NULL; k++)
    {
        word[k] = malloc (strlen (token) + 1);
        strcpy (word[k], token);
        token = strtok (NULL, delim);
        printf ("%s\n", word[k]);
    }

    count = k;  /* save number of string in word */

    qsort (word, count, sizeof *word, compare_str);     /* sort the array of pointers */

    printf ("\nSorted words in pointer array:\n\n");
    for (k = 0; k < count; k++)
        printf ("%s\n", word[k]);

    for (k = 0; k < count; k++)
    {
        free(word[k]);
    }
}

When you compile, there should be NO warnings:

gcc -Wall -Wextra -o yourprog yourfile.c

Example Use/Output

$ ./bin/str_find_ltr_words
enter some text
the quick brown fox jumped over a lazy dog
Number of Occurrences of Uppercase letters


Number of Occurrences of Lowercase letters

a :     2
b :     1
c :     1
d :     2
e :     3
f :     1
g :     1
h :     1
i :     1
j :     1
k :     1
l :     1
m :     1
n :     1
o :     4
p :     1
q :     1
r :     2
t :     1
u :     2
v :     1
w :     1
x :     1
y :     1
z :     1


Separating and saving words in pointer array:

the
quick
brown
fox
jumped
over
a
lazy
dog


Sorted words in pointer array:

a
brown
dog
fox
jumped
lazy
over
quick
the

And as a final point. There is a lot of irrelevant code in your findWords function. I didn't take the time to strip it out because that wasn't preventing your sort of words. Your code with the modifications above compiles without warning. So I'll leave it up to you to go though findWords and get rid of what isn't needed.


Full Example

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void findLetters(char *ptr);
void findWords(char *point);
void sort_string(char *p);
int compare_str (const void *a, const void *b);


int main (void)
{
    char textStream[100] = {0};     //up to 98 characters and '\n\ and '\0'
    size_t len = 0;

    printf ("enter some text\n");
    if (fgets (textStream, sizeof textStream, stdin)) //input up to 99 characters
    {
        len = strlen (textStream);
        textStream[--len] = 0;      // strip newline from end of textStream

        findLetters (textStream);
        findWords (textStream);
        sort_string (textStream);
    }
    else
    {
        printf("fgets failed\n");
    }

    return 0;
}

void findLetters(char *ptr) //find occurences of all letters
{
    int upLetters[26];
    int loLetters[26];
    int i;
    int index;

    for (i = 0; i < 26; i++) // set array to all zero
    {
        upLetters[i] = 0;
        loLetters[i] = 0;
    }
    i = 0;
    while (ptr[i] != '\0') // loop until prt[i] is '\0'
    {
        if (ptr[i] >= 'A' && ptr[i] <= 'Z') //stores occurrences of uppercase letters
        {
            index = ptr[i] - 'A';// subtract 'A' to get index 0-25
            upLetters[index]++;//add one
        }

        if (ptr[i] >= 'a' && ptr[i] <= 'z') //stores occurrences of lowercase letters
        {
            index = ptr[i] - 'a';//subtract 'a' to get index 0-25
            loLetters[index]++;//add one
        }
        i++;//next character in ptr
    }
    printf("Number of Occurrences of Uppercase letters\n\n");
    for (i = 0; i < 26; i++)//loop through 0 to 25
    {
        if (upLetters[i] > 0)
        {
            printf("%c : \t%d\n", (char)(i + 'A'), upLetters[i]);
            // add 'A' to go from an index back to a character
        }
    }
    printf("\n");
    printf("Number of Occurrences of Lowercase letters\n\n");
    for (i = 0; i < 26; i++)
    {
        if (loLetters[i] > 0)
        {
            printf("%c : \t%d\n", (char)(i + 'a'), loLetters[i]);
            // add 'a' to go back from an index to a character
        }
    }
    printf("\n");
}

void findWords(char *point)
{
    int i, k, count, space;
    int len = strlen (point);
    char *delim = "{ } . , ( ) \n";
    char **word = NULL;
    char *newpoint = NULL;
    char *token = NULL;

    i = k = count = space = 0;

    for (i = 0; i < len; i++) //counts # of spaces between words
        if ((point[i] == ' ') || (point[i] == ',') || (point[i] == '.'))
            space++;

    word = malloc (sizeof *word * space + 1); //allocates memory to array according to number of words
    newpoint = malloc (strlen (point) + 1);
    strcpy (newpoint, point);
    token = strtok (newpoint, delim);

    printf ("\nSeparating and saving words in pointer array:\n\n");
    for (k = 0; token != NULL; k++)
    {
        word[k] = malloc (strlen (token) + 1);
        strcpy (word[k], token);
        token = strtok (NULL, delim);
        printf ("%s\n", word[k]);
    }

    count = k;  /* save number of string in word */

    qsort (word, count, sizeof *word, compare_str);     /* sort the array of pointers */

    printf ("\nSorted words in pointer array:\n\n");
    for (k = 0; k < count; k++)
        printf ("%s\n", word[k]);

    for (k = 0; k < count; k++)
    {
        free(word[k]);
    }
}

void sort_string(char *p)
{
    int c, d = 0, length;
    char *pointer, *result, ch;

    length = strlen(p);
    result = (char*)malloc(length + 1);

    pointer = p;

    for (ch = 'a'; ch <= 'z'; ch++)
    {
        for (c = 0; c < length; c++)
        {
            if (*pointer == ch)
            {
                *(result + d) = *pointer;
                d++;
            }
            pointer++;
        }
        pointer = p;
    }
    *(result + d) = '\0';

    strcpy(p, result);

    free(result);
}

/* qsort C-string comparison function */
int compare_str (const void *a, const void *b)
{
    const char **ia = (const char **)a;
    const char **ib = (const char **)b;
    return strcmp(*ia, *ib);
}

Why you had an extra newline

As mentioned in the comments and in the answer, it is always a good idea to strip the trailing '\n' from your strings when you are reading with fgets or getline. It will cause your character count in len to be off by 1 and then for your space count to be off by 1. Now that in itself isn't a crime, it just causes you to allocate one more pointer than needed. However it has consequences due to your definition of:

char* delim = "{ } . , ( ) ";

Since you do not specify '\n' as a delimiter, strtok happily considers it as a separate word. This does cause problems with your sort as you now have a blank line appearing in your array of words. So you can either strip the newline after you read textStream or add '\n' to delim (or properly both).

char* delim = "{ } . , ( ) \n";

Case Insensitive Sorting

When wanting to sort without the effects of your LOCALE sorting capital letters first, etc. Use strcasecmp instead of strcmp. So above, just change the qsort comparison to:

int compare_str (const void *a, const void *b)
{
    const char **ia = (const char **)a;
    const char **ib = (const char **)b;
    return strcasecmp(*ia, *ib);
}

strcasecmp on Windows

strcasecmp is a non-standard function available on linux and not in windows. To include the same functionality use stricmp instead. See (MSDN stricmp).


Related:


C binary tree sort - extending it


c,binary-tree,binary-search-tree
I need some help in C Help me to extend the binary tree sort on C. I need to return a sorted array in sort function. here it is: #include <stdio.h> #include <stdlib.h> struct btreenode { struct btreenode *leftchild ; int data ; struct btreenode *rightchild ; } ; void...

Segmentation Fault if I don't say int i=0


c,arrays,segmentation-fault,initialization,int
void removeVowels(char* array){ int i,j,v; i=0; char vowel[]={'a','e','i','o','u'}; while(array[i]!='\0') { for(v=0;v<5;v++) { if (array[i]==vowel[v]) { j=i; while(array[j]!='\0') { array[j]=array[j+1]; j++; } i--; break; } } i++; } } in function removeVowels() if I don't include i=0; and just say int i; why does it give segmentation fault? Isn't it automatically...

How does this code print odd and even?


c,if-statement,macros,logic
#define MACRO(num, str) {\ printf("%d", num);\ printf(" is");\ printf(" %s number", str);\ printf("\n");\ } int main(void) { int num; printf("Enter a number: "); scanf("%d", &num); if (num & 1) { MACRO(num, "Odd"); } else { MACRO(num, "Even"); } return 0; } Please explain the above code (if/else condition and how...

getchar() not working in c


c,while-loop,char,scanf,getchar
getchar() is not working in the below program, can anyone help me to solve this out. I tried scanf() function in place of getchar() then also it is not working. I am not able to figure out the root cause of the issue, can anyone please help me. #include<stdio.h> int...

do calculation inside JSONArray in Java


java,arrays,json
I have a simple issue but cannot solve it as I am not very good at algorithm! I have an JSONArray in this form: [{"values":[{"time":1434976493,"value":"50"}, {"time":1434976494,"value":"100"}],"counter":"counter1"}, {"values":[{"time":1434976493,"value":"200"}, {"time":1434976494,"value":"300"}],"counter":"counter2"}, {"values":[{"time":1434976493,"value":"400"}, {"time":1434976494,"value":"600"}],"counter":"total"}] What I want to do is to get the integer value for counter 1 and counter 2 and then divide...

Ruby: How to copy the multidimensional array in new array?


ruby-on-rails,arrays,ruby,multidimensional-array
seating_arrangement [ [:first, :second, :none], [:first, :none, :second], [:second, :second, :first], ] I need to copy this array into new array. I tried to do it by following code: class Simulator @@current_state def initialize(seating_arrangement) @@current_state = seating_arrangement.dup end But whenever I am making any changes to seating_arrangement current_state changes automatically....

pointer to pointer dynamic array in C++


c++,arrays,pointers
I've been having bad luck with dynamic pointers when I want to close it. why the application wrote to memory after end of heap buffer? how can I close my array? int main() { . . int **W; W = new int* [n]; for (int i=1; i <= n; i++)...

jQuery - Value in Function


jquery,arrays,function
My array: array.name = "Thiago"; array.date = "01/01/1990"; I want a function like this: function myFunc( array, fieldToCompare, valueToCompare ) { if( array.fieldToCompare == "Thiago" ) alert(true); } myFunc( myArray, name, "Thiago" ); is it possible?...

Does realloc() invalidate all pointers?


c,pointers,dynamic-memory-allocation,behavior,realloc
Note, this question is not asking if realloc() invalidates pointers within the original block, but if it invalidates all the other pointers. I'm new to C, and am a bit confused about the nature of realloc(), specifically if it moves any other memory. For example: void* ptr1 = malloc(2); void*...

accessing range of values in arduino array


arrays,arduino
I have data packet coming in like this in Arduino. Data: 12345678901234 I can access the 5th value using the code below. id = sx1272.packet_received.data[4]; My question is how do I access a rang of values? I tried this, but the colon throws an error. char[2] id; if( sx1272.packet_received.length >...

Reverse ^ operator for decryption


c,algorithm,security,math,encryption
I'm trying to reverse the following code in order to provide a function which takes the buffer and decrypts it. void crypt_buffer(unsigned char *buffer, size_t size, char *key) { size_t i; int j; j = 0; for(i = 0; i < size; i++) { if(j >= KEY_SIZE) j = 0;...

Loop through database table and compare user input


mysql,c
I am trying to loop through the rows in a MySql table and compare the data in a certain column to some user input using C. Currently my code looks like this: MYSQL *cxn = mysql_init(NULL); MYSQL_RES *result; unsigned int num_fields; unsigned int num_rows; char *query_string; MYSQL_ROW *row; if (mysql_real_connect(cxn,...

Infinite loop with fread


c,arrays,loops,malloc,fread
I'm trying to allocate an array 64 bytes in size and then loop over the array indexes to put a read a byte each from the inputfile. but when I don't malloc() the array indexes, the loop stays in index0 (so each time it loops it replaces the content in...

Blank screen on GridView


android,arrays,gridview
I'm trying to create a GridView with an array of strings. These are XML, and MainActivity and Adapter, but what I get is a blank screen. I'm change the background, but the result is the same, but clicking on a point on the screen appears to me the toast stating...

What does `strcpy(x+1, SEQX)` do?


c,strcpy
I'm wondering what this syntax of strcpy() does in line 65 and 66: 24 #define SEQX "TTCATA" 25 #define SEQY "TGCTCGTA" 61 M = strlen(SEQX); 62 N = strlen(SEQY); 63 x = malloc(sizeof(char) * (M+2)); /* +2: leading blank, and trailing \0 */ 64 y = malloc(sizeof(char) * (N+2)); 65...

How to innerHTML a function with array as parameter?


javascript,arrays,loops,foreach,innerhtml
I am learning about looping thorugh arrays - I want to pass the result of an if else statement in the forEach function (inside another function with array as parameter) to HTML using innerHTML (does not have to be innerHTML if you know better methods I do not mind). It...

array and function php


php,arrays
I'm just a beginner in PHP coding. I've been reading through a tutorial, but having some trouble with basic PHP concepts. If you could help me, I'd be much obliged. I'm having trouble understanding why the following code doesn't work. <?php function sum($x, $y) { $z = $x + $y;...

scanf get multiple values at once


c,char,segmentation-fault,user-input,scanf
I need to get in one single shot different inputs from one single line. In particular I need to get a single char and then, depending on which char value I just read, it can be a string and an int or a string, an int and another string and...

Segmentation fault with generating an RSA and saving in ASN.1/DER?


c,openssl,cryptography,rsa
#include <string.h> #include <openssl/aes.h> #include <openssl/rand.h> #include <openssl/bio.h> #include <openssl/rsa.h> #include <openssl/evp.h> #include <openssl/pem.h> #define RSA_LEN 2048 #define RSA_FACTOR 65537 int genRSA2048(unsigned char **pub,unsigned int *pub_l,unsigned char **priv,unsigned int *priv_l){ RSA *pRSA = NULL; pRSA = RSA_generate_key(RSA_LEN,RSA_FACTOR,NULL,NULL); if (pRSA){ pub_l = malloc(sizeof(pub_l)); *pub_l = i2d_RSAPublicKey(pRSA,pub); priv_l = malloc(sizeof(priv_l));...

How do I print more than one value per key in Tcl?


arrays,tcl
array set array_in_twos { set1 table set2 chair set1 chair } foreach combo [array names array_in_twos] { puts "$combo is $array_in_twos($combo)," } outputs: set1 is chair, set2 is chair, It seems the second 'set 1' replaces the first 'set 1'. how do i print all? set1 is table, set2 is...

SCALA: change the separator in Array


arrays,string,scala,delimiter
I have an Array like this. scala> var x=Array("a","x,y","b") x: Array[String] = Array(a, x,y, b) How do I change the separator comma in array to a :. And finally convert it to string like this. String = "a:x,y:b" My aim is to change the comma(separators only) to other separator(say,:), so...

Array in Foreach (CodeIgniter)


php,arrays,codeigniter,foreach
I want to use array in foreach loop but failed, here is my code: foreach($this->db->get_where('mytable', array('result' => '1 or 2', 'id' => 'foo'))->result_array() I think 'result' => '1 or 2'piece has a problem but I couldn't find out how can I use array in this kind of foreach. I want...

How to read string until two consecutive spaces?


c,format,sscanf,c-strings
A well known function of the scanf() functions is that you can pass a format to scan input according to this format. For my case, I cannot seem to find a solution searching this and this documentation. I have a string (sInput) as the following: #something VAR1 this is a...

Select word between two words


javascript,arrays,jquery-selectors
How can I create a function that selects everything between the words X and Y and pushes it to an array. By Greili - 4 Hours and 40 Minutes ago. #NsShinyGiveaway 0 comments By ToneBob - 4 Hours and 49 Minutes ago. #NsShinyGiveaway 0 comments By hela222 - 5 Hours...

Disadvantages of calling realloc in a loop


c,memory-management,out-of-memory,realloc
I'm trying to implement some math algorithms in C on Windows 7, and I need to repeatedly increase size of my array. Sometimes it fails because realloc can't allocate memory. But if I allocate a lot of memory at once in the beginning it works fine. Is it a problem...

Having two arrays in variable php


php,mysql,arrays,variables,multidimensional-array
i've this code, i'm trying to explode my date e.g "04 June 2015" to have the day and the month in other 2 variables, but i have all in a method, with an array, is it possible, my code doesn't work, it writes "Array[0]" why? while ($i < $number) {...

most efficient way to create javascript array out of various php arrays


javascript,php,jquery,arrays
I have a form that a user can submit multiple times, adding different information each time. These form inputs are translated into php $_SESSION arrays, so each time the user hits the submit button, the array grows. This is working fine. I need to bring these over into javascript but...

Array JLabel ActionListener multiple JPanels


java,arrays,swing
I have an array of JLabels and I want to add an ActionListener to them. Every label should display a panel and the other should be removed. How can I realize this?

Comparing arrays with numbers in vb.net


arrays,vb.net
I need a way to compare two arrays in vb.net and save result in third array: Dim KonRes(3) As Integer Dim UserRes(3) As Integer Dim YelRed(3) As Integer KonRes(0) = 1 KonRes(1) = 2 KonRes(2) = 3 KonRes(3) = 4 UserRes(0) = 4 UserRes(1) = 3 UserRes(2) = 2 UserRes(3)...

Translating a character array into a integer string in C++


c++,arrays,string
I was trying to achieve translating a character array into a integer string and corresponding character to their alphabetical order. For instance: A(a) = 0 , Z(z) = 25. string key_char = argv[1]; string key_num; for (int i = 0; i < key_char.length(); i++){ if (isalpha(key_char[i])){ if (islower(key_char[i])){ key_num[i] =...

Javascript function to validate contents of an array


javascript,arrays
Here's what is asked: validItems(items) – this function receives a string array of items which are to be for a customer. The function returns an empty string indicating all item codes in the array are valid; otherwise the function returns the first invalid item code in the array. All item...

Perl: Using Text::CSV to print AoH


arrays,perl,csv
I have an array of hashes (AoH) which looks like this: $VAR1 = [ { 'Unit' => 'M', 'Size' => '321', 'User' => 'test' } { 'Unit' => 'M' 'Size' => '0.24' 'User' => 'test1' } ... ]; How do I write my AoH to a CSV file with separators,...

Split an array into slices, with groupings


arrays,ruby,enumerable
I've got some Ruby code here, that works, but I'm certain I'm not doing it as efficiently as I can. I have an Array of Objects, along this line: [ { name: "foo1", location: "new york" }, { name: "foo2", location: "new york" }, { name: "foo3", location: "new york"...

Javascript: Labeling array results


javascript,arrays
Alright so here is my Html code: <html> <head> <title>Planning</title> <script type="text/javascript" src="Function.js"></script> </head> <body> <form id="form"> <h1><b>Please enter data</b></h1> <hr size="3"/> <br> <label for="Name">Name:</label> <input id="Name" type="text" /> <br> <label for="Date">Date: </label><input id="Date" type="text" /> <br> <label for="Plans">Plans:...

Get elements containing text from array


javascript,jquery,html,arrays,contains
I want to search all the elements containing any string in the array. For example I have following list of items <ul> <li>cricket bat</li> <li>tennis ball</li> <li>golf ball</li> <li>hockey stick</li> </ul> and this array var arr = ['bat', 'ball']; It should select all the elements having text bat and ball....

C++ & Qt: Random string from an array area


c++,arrays,string,qt,random
In my small Qt application, I want to pick a random string out of an array after I clicked on a button. I've read many threads but nothing works for me. So in my slot there's an array with several strings in it. I also implemented <string>, <time.h> and srand....

Zipping two arrays together with index in Scala?


arrays,scala,zip
I have two arrays populated with integers. They are the same size (val array1 and val array2). I want to fuse them together into tuples with their index as the third element. For example if we have val array1 = Array(5,2,6,2) and val array2 = Array(9,8,3,4) then I want to...

Create array from another with specific indices


javascript,arrays
I have two arrays, one of data and one of indices: var data = [ 'h', 'e', 'l', 'l', 'o', ' ' ]; var indices = [ 4, 0, 5, 0, 1, 2, 2 ]; I would like to create a third array, using cells of data in order indicated...

How to pivot array into another array in Ruby


arrays,ruby,csv
I have a multidimensional array like this one : myArray = [["Alaska","Rain","3"],["Alaska","Snow","4"],["Alabama","Snow","2"],["Alabama","Hail","1"]] I would like to end up with CSV output like this. State,Snow,Rain,Hail Alaska,4,3,nil Alabama,2,nil,1 I know that to get this outputted to CSV the way I want it I have to have output array like this: outputArray =[["State","Snow","Rain","Hail"],["Alaska",4,3,nil],["Alabama",2,nil,1]]...

Merge and sum values and put them in an array


javascript,arrays,angularjs,foreach
I'm retrieving values from an external source and apply a foreach loop to the results, with the code below. angular.forEach(data, function(value, key) { if (value.start_date > firstdayOfWeek && value.start_date < lastdayOfWeek) { console.log(value.firstname + ' - ' + value.distance); } else { //do nothing } }); The result is console...

Notice: Array to string conversion in “path of php file” on line 64


php,mysql,arrays,oracle
PHP CODE -: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> </head> <body> <?php $rows =0; $fp = fopen("leave1.csv","r"); if($fp){ while(!feof($fp)){ $content = fgets($fp); if($content) $rows++; } } fclose($fp); //echo $rows; $_SESSION['rows'] = $rows; ?>...

Substring of a file


javascript,arrays,substring
I have a file that is structure like this : var file = "a|b|c|d, a|b|c|d, a|b|c|d, a|b|c|d, a|b|c|d"; Now I would extract all letters "c" and "d" of this file and put those letter in array, structure like this: var array = [ [a,b,1], [a,b,2], [a,b,3], [a,b,4], [a,b,5] ]; How...

How to check if data already exists then randomly generate new data from an Array


php,mysql,arrays,mysqli
Okay so, I made an array containing 270+ different strings. The main goal is too echo out 60 strings from that array and combine them.. Ex. 1.String, 1.String2. The 2 echo'd out strings are a combination, and should be together like 1-1 and 2-2, 3-3, and ect. In total there...

Javascript sort array of objects in reverse chronological order


javascript,arrays,sorting
I have an array of objects which holds a list of jobs and I would like to sort them in reverse chronological order as they would appear on a resume for example. I came up with the below solution which 'seems' to work but I was wondering if there is...

C programming - Confusion regarding curly braces


c,scope
The following code is for replacing multiple consecutive spaces into 1 space. Although I manage to do it, I am confused in the use of curly braces. This one is actually running fine: #include <stdio.h> #include <stdlib.h> int main() { int ch, lastch; lastch = 'a'; while((ch = getchar())!= EOF)...

Galois LFSR - how to specify the output bit number


c,prng,shift-register
I am trying to understand how change the galois LFSR code to be able to specify the output bit number as a parameter for the function mentioned below. I mean I need to return not the last bit of LFSR as output bit, but any bit of the LFSR (...

How to pass array in rails 4 strong parameters


ruby-on-rails,arrays
I have to pass a array of food_item_ids in my order_controller. Every order will have many food_items. How can I pass these food_items_id as an array in strong parameters. orders_controller.rb def create @order = Order.new(order_params) if @order.save render :json, @order, status:201, location: [:api, @order] else render :json, { errors: @order.errors...

Is there Predefined-Macros define about byte order in armcc


c,armcc,predefined-macro
Is there Predefined-Macros define about byte order in armcc. I am a novice on the armcc.and sorry for my English. In gcc these are macros: __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__ __ORDER_BIG_ENDIAN__ __ORDER_PDP_ENDIAN__ ... Now I have to use armcc, Is there same like these with armcc? Thank a lot. by the way,the armcc...