I am taking a beginner's course in C, and trying to wrap my head around "strings". I have previously programmed in Java, so it is a bit confusing.
I am wondering how to split a "string" into characters , so as to be able to remove certain characters. I have written code for a linked list, with each node holding a data value, as well as a next pointer (calling it node_line, as it holds lines).
typedef struct node {
char *data;
struct node *next;
} node_line;
This works without problems, and I can traverse the entire list and print out each element:
void print_list(node_line head) {
node_line * current = head;
while(current != NULL) {
printf("%s\n", current->data);
current = current->next;
}
}
However, I am having problems with converting the "string" in current->data into characters. That is, reading one character at a time.
For instance, I want to write a program that removes all the vowels in a "string". I have managed to solve this when reading a file, using the getc() function. However, I can't seem to do so with the text in current-> data.
int c;
while((c = getc(f)) != EOF) {
//REMOVE
if(c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || c=='y') {
printf(""); //Remove the vowel
}
else {
putchar(c); //Write out one character at the time.
}
}
I imagine it being something like:
while ((c = getc(current->data) != NULL) { ... }
Any help, tips, etc. are highly appreciated!
getc
is for reading from files . To access chars in a char *
buffer (string) you would typically do something like this:
for (const char * p = current->data; *p != '\0'; ++p)
{
char c = *p;
if (c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || c=='y') {
...
}
}
Or if you prefer explicit array indexing rather than pointers:
const char * s = current->data;
for (int i = 0; i < strlen(s); ++i)
{
char c = s[i];
if (c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || c=='y') {
...
}
}
void print_list(node_line head) {
should be
void print_list(node_line *head) {
getc:
Returns the character currently pointed by the internal file position indicator of the specified stream.
That's not what you want, use pointer arithmetic:
char *s = current->data;
while (*s) {
if(*s=='a' || *s=='e' || *s=='i' || *s=='o' || *s=='u' || *s=='y') {
printf(""); //Remove the vowel
}
else {
putchar(*s); //Write out one character at the time.
}
s++;
}
or better:
char *s = current->data;
while (*s) {
if(*s!='a' && *s!='e' && *s!='i' && *s!='o' && *s!='u' && *s!='y') {
putchar(*s); //Write out one character at the time.
}
s++;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.