1

Is there a way to create a string of characters from a set of elements taken from a existing array?

Example: say I have an array of four characters

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

int main (void)
{
char abcd[] = "abcd";
string sabcd = "0";
}

Is there a way I can create strings with a subset of array elements, such as "ac", "cd" and so on?

Edited: added libraries for clarification.

6
  • 5
    there is no string type in c Commented Sep 28, 2017 at 7:13
  • 1
    Technically the array abcd is an array of five characters, since it will include the string terminator. Commented Sep 28, 2017 at 7:14
  • GO to this sanfoundry.com/c-program-find-subsets-of-string Commented Sep 28, 2017 at 7:16
  • 1
    As for your problem, how about char ac[3] = { abcd[0], abcd[2], '\0' };? You can of course set up the new array ac using a loop and some suitable condition for which characters to include. Perhaps if you try something and have problem with your attempt, then you can come back with a new question including a Minimal, Complete, and Verifiable Example and ask for help with whatever problem you have then. Also take some time to read about how to ask good questions. Commented Sep 28, 2017 at 7:16
  • Sorry, I thought this short code was enough to make my point. I am working on something bigger but is messy and does not seem right to post it here. I will read your suggestion. Thanks. Commented Sep 28, 2017 at 7:29

2 Answers 2

1

You could always index the characters you wish your substring to have.

For example:

char adb[4] = {abcd[0], abcd[3], abcd[1], '\0'};

Another approach is to use strncpy(), like this:

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

int main (void)
{
    char abcd[] = "abcd";
    char bc[3] = "";
    strncpy(bc, abcd + 1, 2);
    puts(bc);
}

Output:

bc

Sign up to request clarification or add additional context in comments.

Comments

1

you can iterate over the array elements like this:

char abcd[] = "abcd";

for(int i=0; i<4; i++){
    for(int j=i; j<4; j++){
        d = abcd[i] + abcd[j];
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.