0

Hi I'm new to C and I'm having trouble finding a way of printing only the 4th, 5th or 10th letter of a String.

I've got this little code:

char firstWord[100];
char secondWord[100];

printf("Please type in: Hello World\n");
fgets(firstWord, sizeof(firstWord), stdin);

printf("Please type in: How are you?\n");
fgets(secondWord, sizeof(secondWord), stdin);

printf("You typed: %s,%s", firstWord, secondWord);

strcat(firstWord, secondWord);

printf("together it looks like this: %s", firstWord);

Now how would I print for instance the 4th or the 6th character only of the concatenated string?

  • Welcome to StackOverflow. I would advise you to take a good book on C. This can be done by using `[]`, but you'd rather make sure the concatenated string is long enough to have a 4th, 5th or 10th letter first. – Eregrith Oct 23 '13 at 15:55

3 Answers3

1

A string in C is just an array of chars (with a '\0' at the end), so you can access the individual characters with an array-subscript:

printf("%c", firstWord[3]); // don't forget 4th element is at [3] 
                            // & use %c for char
Kninnug
  • 7,992
  • 1
  • 30
  • 42
0

Try this

printf("%c", firstword[3]); // for 4th character
haccks
  • 104,019
  • 25
  • 176
  • 264
0

Since you're using array style char strings, you can just:

    printf("%c", firstWord[3]);

For the fourth letter, and on like that. The reason it's 3 is because the array indexing starts at zero, so the first term is in the zero element, second term in the first element, etc. Then you just continue that way with all of them.

It's a lot easier if you have a pattern, though, because then you can just code a loop on the pattern, and it won't take as much effort on the coder's part.

ciphermagi
  • 747
  • 3
  • 14