1,105,585 Community Members

How to extract the first letter of a c-string?

Member Avatar
pearle
Newbie Poster
12 posts since Feb 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Suppose I have something like

char *threeDays[3] = {"Monday","Tuesday","Wednesday"};

and I wanted to extract the first letter of each string and create another string using those letters. How would I go about doing it? I tried

char str[4];
strcpy(str,*(threeDays+1));
strcat(str,*(threeDays+2));

but that gives me "TuesdayWednesday". I just want a string with the first letters ("MTW"). Can anyone help?

Note: I cannot use the string class. I have to use c-strings.

Member Avatar
WaltP
Posting Sage w/ dash of thyme
9,363 posts since May 2006
Reputation Points: 2,905 [?]
Q&As Helped to Solve: 1,151 [?]
Skill Endorsements: 45 [?]
Team Colleague
 
0
 

threeDays[0][0] = 'M'
threeDays[0][1] = 'o'
threeDays[0][2] = 'n'
threeDays[1][0] = 'T'
threeDays[2][0] = 'W'

Member Avatar
pearle
Newbie Poster
12 posts since Feb 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

When I try, for example,

strcpy(str,threeDays[0][0])

I get an error saying "invalid conversion from 'const char' to 'const char*'; initializing argument 2 of `char* strcpy(char*, const char*)' "... :(

Member Avatar
WaltP
Posting Sage w/ dash of thyme
9,363 posts since May 2006
Reputation Points: 2,905 [?]
Q&As Helped to Solve: 1,151 [?]
Skill Endorsements: 45 [?]
Team Colleague
 
0
 

When I try, for example,

strcpy(str,threeDays[0][0])

I get an error saying "invalid conversion from 'const char' to 'const char*'; initializing argument 2 of `char* strcpy(char*, const char*)' "... :(

That's because it is very wrong. See my other post for a clue.

Member Avatar
WaltP
Posting Sage w/ dash of thyme
9,363 posts since May 2006
Reputation Points: 2,905 [?]
Q&As Helped to Solve: 1,151 [?]
Skill Endorsements: 45 [?]
Team Colleague
 
0
 

Additional:
Just copy the characters into the character array, adding \0 as the last character.

Remember, in C as 'string' is simply an array of characters ending with \0. It's not a special thing, it's not magic. It's just an array of characters by another name.

Member Avatar
pearle
Newbie Poster
12 posts since Feb 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Thanks so much for the help! I got my program to work. :)

Question Answered as of 4 Years Ago by WaltP
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article