George David King
George David King

Reputation: 221

How can I get more than one character from a string in c

I know that this might be sounded really easy for you but I've done a research in the internet and I didn't find what I was looking for. I want to take from a string more than one character. For example:

char str1[10];  
printf("Give me a word: \n") ;
gets(str1);

Let's say that I'm gonna type the word: Stack. How can I get two side by side characters from this string? For example:

char str2[10];

Is there a way in order str2=tac ?

Upvotes: 0

Views: 409

Answers (3)

Sedat Gokcen
Sedat Gokcen

Reputation: 3270

int i;
char str1[] = "Stack";
char str2[10];

for (i = 1; i < 4; i++)
    str2[j++] = str1[i];

str2[j] = "\0";

It will return "tac". You can write a simple function about this. Your function should take 2 parameters, first letter you want and last letter you want.

So in this case:

1 --> first letter you want

4 --> last letter you want

I edited my code with Jonathan's solution. If you didn't understand that solution, you can also look at this:

for (i = 1, j = 0; i < 4 && j < 3; i++, j++)
    str2[j] = str1[i];

Upvotes: 2

Kozos
Kozos

Reputation: 39

http://www.tutorialspoint.com/c_standard_library/c_function_gets.htm

I think this is what you are looking for. :)

Upvotes: -1

alex
alex

Reputation: 490153

Start a pointer at the offset and seek through the string until you get to the null byte, storing the new string somewhere else.

Upvotes: 0

Related Questions