Concatenating array of strings into one string separated by spaces


 
Thread Tools Search this Thread
Top Forums Programming Concatenating array of strings into one string separated by spaces
# 1  
Old 01-17-2009
Concatenating array of strings into one string separated by spaces

Hi,

Well as the title says, I have an array of strings (delimited by null). The length of the array is variable and length of each string is variable as well. What I need is one huge string with the original strings in the array separated by spaces.

For example is an array is such that array[0] = Firstname, array[1] = Secondname, I want to be able to extract that and store it in a char * which would then be "firstname Secondname".

Please tell how I would go about doing this.

Thanks.
# 2  
Old 01-18-2009
Hi,

So I figured out how to do it. In case, anybody else are looking for the same thing, I am posting my version here:

Code:
/*                                                                            
 * Subroutine to extract the full name by concatenating                       
 * array of strings into one full string separated by spaces.                 
 *                                                                            
 * Input: number of fields and array of strings                               
 * Returns: full string name (char *)                                         
 */                                                                           
                                                                              
char *get_full_name(int n, char **f){                                         
    int tot_length = 1, i;                                                    
    char *p, *result;                                                         
    const char *current;                                                      
    for (i = 1; i < n; i++){                                                  
        tot_length += strlen(f[i]) + 1;                                       
    }                                                                         
    result = (char *) malloc ((unsigned) tot_length);                         
    for (p = result, i = 1; i < n; i++){                                      
        current = f[i];                                                       
        if (strlen(current) == 0){                                            
            continue;                                                         
        }                                                                     
        memcpy(p, current, (size_t) strlen(current));                         
        p += strlen(current);                                                 
        *p = ' ';                                                             
        p++;                                                                  
    }                                                                         
    return (result);                                                          
}

I am not sure whether it is the perfect way to do it..but it works Smilie.

Thanks.
# 3  
Old 01-18-2009
I can see a couple of problems already. You are assuming arrays in C index from 1 instead of 0. You are adding a trailing space to your result string. You are not adding a '\0' to the end of your result string.
# 4  
Old 01-18-2009
Hi,

Thanks for your comments. The index problem is actually not a problem because this function is part of a program I am writing and I know that whatever I need will start from index 1 (because I am passing it that way). That can be changed here.

Could I just add a null at the end of result like say:

result--;
*result = '\0';

Although this didnt work for me.
# 5  
Old 01-18-2009
Yes, that should work.
# 6  
Old 01-18-2009
Here is a version of your code which eliminates (a) 2 calls to strlen() and (b) the need to pass the number of array elements to get_full_name().
Code:
#include <stdio.h>
#include <string.h>

char *
get_full_name(char *f[])
{
    int tot_length = 1, i, len;
    char *p, *result;

    for ( i = 0; f[i] != NULL; i++)
        tot_length += strlen(f[i]) + 1;

    result = (char *)malloc((unsigned) tot_length);

    for (p = result, i = 0; f[i] != NULL; i++)
    {
        if (!(len = strlen(f[i])))
            continue;
        memcpy(p, f[i], (size_t)len);
        p += len;
        *p++ = ' ';
    }

    if (p > result)
       --p;
    *p='\0';

    return (result);
}

int
main(int argc, char **argv)
{
    char *namestr[] = {"John", "Quincy", "Adams", NULL};
    char *result;

    result = get_full_name(namestr);

    printf("Result: <%s>\n", result);

    exit(0);
}

# 7  
Old 01-19-2009
Timtowtdi

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

char *get_full_name(const char **t)
{
    char *f=NULL;
    
    while (*t) {
        f = (char *) realloc(f, strlen(*t)+strlen(f)+1);
        sprintf(f,"%s%s%s",f,(strlen(f)?" ":""),*t++);
    }
    return f;
}

int main(int argc, char **argv)
{
    const char *str[] = {"John", "Quincy", "Adams", NULL};
    char *res;

    res = get_full_name(str);
    printf("Result: <%s>\n", res);
    return 0;
}

Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Concatenating 2 lines from 2 files having matching strings

Hello All Unix Users, I am still new to Unix, however I am eager to learn it.. I have 2 files, some lines have some matching substrings, I would like to concatenate these lines into one lines, leaving other untouched. Here below is an example for that.. File 1 (fasta file): >292183... (6 Replies)
Discussion started by: Mohamed EL Hadi
6 Replies

2. Shell Programming and Scripting

Lex: concatenating word into array of c-strings

Alright, so I'm writing a file for the lexical analyzer (lex). It will be used to check C code (collecting the identifiers and storing those names along with the line numbers the identifier was found on). I'm not used to 'C' so I'm having some difficulty. I am using a function (insertId()) to... (4 Replies)
Discussion started by: D2K
4 Replies

3. Shell Programming and Scripting

Loop through array of arrays of string with spaces

Hi I'm trying to loop through an array that contains other arrays and these arrays consist of strings with spaces. The problem is that I can't seem to preserve the spacing in the string. The string with spaces are either divided into multiple items if I change IFS to \n or all the elements of... (4 Replies)
Discussion started by: kidmanos
4 Replies

4. Shell Programming and Scripting

Concatenating words without spaces.

Hi All, I have written a C program to solve this problem but I am eager to know whether the same output can be obtained using sed or awk? This is the input: star ferry computer symbol prime time This is the output: starferry ferrycomputer computersymbol symbolprime primetime (7 Replies)
Discussion started by: shoaibjameel123
7 Replies

5. Shell Programming and Scripting

grep on string separated by spaces

hi I am on AIX 5 and i have a script that runs the following command to list processes running. I then want to kill the returned processes. The PID are on field 2 separated by spaces. $ ps -ef|grep "rams.e $PORT" lesqa 1826998 2646248 0 11:20:35 pts/2 0:00 grep rams.e t24cm 2789380 ... (3 Replies)
Discussion started by: dustytina
3 Replies

6. Shell Programming and Scripting

Concatenating strings and run it in bash

Hi, all, I tried to write a simple shell script as follow: #!/bin/bash # What want to do in bash is following # : pcd_viewer cloud_cluster_0.pcd cloud_cluster_1.pcd cloud_cluster_2.pcd cloud_cluster_3.pcd cloud_cluster_4.pcd STR = "pcd_viewer" for i in `seq 0 4` do STR... (1 Reply)
Discussion started by: bedeK
1 Replies

7. Shell Programming and Scripting

Problem in concatenating two Strings

Hi Friends, I'm new to shell scripting and trying to concatenate two Strings to create a filepath like string but I'm getting an unexpected result. here is my code for 'runToneUserLoad.sh': script_dir="$(dirname $0)" echo "Script Dir:$script_dir" dirtest1="/installedUtility"... (6 Replies)
Discussion started by: kuldeept
6 Replies

8. Shell Programming and Scripting

concatenating strings

I m new to shell scripting and what i want is take as an i/p from command line the name of the file and inside my script i should redirect the o/p of my few commands to this file concatenated with .txt for example if i give ./linux filename i should get the o/p in filename.txt i need to... (2 Replies)
Discussion started by: tulip
2 Replies

9. Shell Programming and Scripting

concatenating strings..

hey guys.. probably a simple question but i cant seem to find any info on it. i have a small array of strings, and i want to concatenate the contents of the array into one big string. any ideas on how i can do this? cheers. (2 Replies)
Discussion started by: jt_csv
2 Replies

10. Shell Programming and Scripting

Concatenating Strings

Is there any function to concatenate strings in shell script (2 Replies)
Discussion started by: radhika03
2 Replies
Login or Register to Ask a Question