Reputation: 65
I am writing a function that is supposed to get an array with a tweet inside it and an empty array which should be filled with usernames that are in the tweet starting with '@' each in its own line. The usernames in the username array should be without the '@'.
This is what I have so far, but this version only stores one username and doesn't even put a new line behind it, and I don't know why.
It's probably a logic mistake?
void extract_username(char *tweet, char *user){
int j = 0;
int z = 0;
for(int i = 0; i<strlen(tweet); i++){
if(tweet[i] == '@'){
z = i+1;
while(tweet[z] != ' '){
user[j] = tweet[z];
z++;
j++;
}
j++;
user[j] = '\n';
}
}
}
extract_username gets called in the main like this
int main(){
char tweet[281];
char user[281]; //for example @user1 hello @user2
printf("Please enter a tweet (max. 280 symbols): \n");
fgets(tweet, 281, stdin);
extract_usename(tweet, user);
printf("%s", user);
return 0;
}
Upvotes: 0
Views: 159
Reputation: 11750
Making the fewest changes possible, change the condition to while (tweet[z] != ' ' && tweet[z] != 0)
and add the newline with user[j++] = '\n';
Probably best to explicitly add the NUL terminator at the end with user[j] = 0;
as well.
void extract_username(char* tweet, char* user) {
int j = 0;
int z = 0;
for (int i = 0; i < strlen(tweet); i++) {
if (tweet[i] == '@') {
z = i + 1;
while (tweet[z] != ' ' && tweet[z] != 0) {
user[j] = tweet[z];
z++;
j++;
}
user[j++] = '\n';
}
}
user[j] = 0;
}
Upvotes: 2