I'm new to C and I'm having some troubles with pointers.
In one function (used to print the words) I have a parameter const char *description, which is pointing to a string or char array like "There is a faint outline of a face visible".
In another function I'm going to have a pointer which points to the first character in the description, then move along until it finds a non-space.
char *pointerToFindFirstChar(char *description){
/* Get my pointer to point to first char in description*/
while (*pointerToFindFirstChar == ' ');
pointerToFindFirstChar++;
return pointer
}
I am unsure how I can do that though.
what I'm trying to achieve is to find the first non space character in a string which is being pointed at by description and store that in another pointer.(hope that makes sense)
Try this:
char *pointerToFindFirstChar(char *description)
{
while(*description == ' ')
description++;
return description;
}
Note that checking for the null byte at the end of the string is unnecessary, as when *pointer == '\0', the condition on the while loop while be false and the loop will end anyway.
Getting rid of the ; at the end of the while line is important; otherwise, the loop will have no body and either run 0 times or infinitely (since pointer would never be changed in the loop). If it ran 0 times, then the increment would happen after exiting the loop.
char *find_first_char(char *desc)
{
while (*desc == ' ') desc++;
return desc;
}
Just for the record, it is possible to have the post-increment directly in the condition of the loop:
char *pointerToFindFirstChar(char *description)
{
while (*description++ == ' ');
return description;
}
In this case you do have an empty loop body because the increment is performed right after the evaluation of the pointer inside the loop condition.
You are currently looking for any different character in your char array. That can also be an exclamation mark or a colon.
Wouldn't it be better to use something like isalnum() or isalpha() ?
If you are looking for a Digit (0-9) or Alpha-char (a-z or A-Z) then use isalnum else use isalpha.
char * pointerToFindFirstChar(char * description)
{
while(*description && !isalnum(*description))
description++;
return description;
}
or
char * pointerToFindFirstChar(char * description)
{
while(*description && !isalpha(*description))
description++;
return description;
}
It'll add some overhead though. Also, checking for the end of the char array would be required in this case.
An other option would be is to use isspace() this will check for any white-space character.
See here for these function descriptions: http://www.java2s.com/Code/C/ctype.h/Catalogctype.h.htm
Related
I have a question regarding char pointers.
I am reading a file in C, using fgets. This is a short overview so you can understand what I would like to do:
char configline[configmax_len + 1]; //configmax_len is the max value I need
while(fgets(configline, sizeof(configline), config){ //config is the file
char *configvalue = strtok(configline, " ");
if (configvalue[0] == "#"){
continue;
}
…
}
char * configvalue is a pointer to the current line being read. What I would like to check is if the first character of the line is a "#".
However when I do the if statement: if (configvalue[0] == "#"), the compiler throws an error: comparison between pointer and integer.
How could I check if the first character of the string a pointer is pointing to is a certain value?
try using
if (configvalue[0] == '#'){
this should compile nicely
Use single quotes to denote a single character; double quotes denote strings, which are represented by a pointer to the first character, hence the error message.
Strtok returns a pointer to a nul terminated string, but you're comparing this with a string constant using ==:
if (configvalue[0] == "#")
Firstly, configvalue is a pointer, so you could do something like:
if (*configvalue == '#')
To dereference the pointer and get the first character in the output string.
This is in Ansi C. I am given a string. I am supposed to create a method that returns an array of character pointers that point to the beginning of each word of said string. I am not allowed to use Malloc, but instead told that the maximum length of input will be 80.
Also, before anyone flames me for not searching the forum, I can't use strtok :(
char input[80] = "hello world, please tokenize this string"
and the output of the method should have 6 elements;
output[0] points to the "h",
output[1] points to the "w",
and so on.
How should I write the method?
Also, I need a similar method to handle input from a file with maximum of 110 lines.
Pseudocode:
boolean isInWord = false
while (*ptr != NUL character) {
if (!isInWord and isWordCharacter(*ptr)) {
isInWord = true
save ptr
} else if (isInWord and !isWordCharacter(*ptr)) {
isInWord = false
}
increment ptr
}
isWordCharacter checks whether the character is part of the word or not. Depending on your definition, it can be only alphabet character (recognize part-time as 2 words), or it may include - (recognize part-time as one word).
Because it's homework here's a part of what you might need:
char* readPtr = input;
char* wordPtr = input;
int wordCount = 0;
while (*readPtr++ != ' ');
/* Here we have a word from wordPtr to readPtr-1 */
output[wordCount++] = /* something... :) */
You'll need that in a loop, and must consider how to move onto the next word, and check for end of input.
I have a binary search function I am passing a pointer character array, the length of that array, a search pointer character array and another counter for something else.
int binarySearch(char* charArray, int len, char* searchItem, int counter)
{
int position;
int begin = 0;
int end = len-1;
int cond =0;
while(begin <= end)
{
position = (begin + end)/2;
// searchItem is a pointer array and the value I want to compare to is
// at the index of counter (determined outside of this function)
if((cond = strcmp(&charArray[position], &searchItem[counter])) == 0)
{
return position;
}
else if(cond < 0){
begin = position + 1;
}
else
end = position - 1;
}
return -1;
}
From here, going through the code by hand seems to make me want to think it should work fine, however it doesn't. I think I'm getting thrown off somewhere along the lines of my pointers and how I'm referring to them so the wrong data is being compared.
I've looked at it for too long now... really need some help here.
It is not very clear what is being searched in what. But I'm guessing that you are searching for a character in a sorted character array. If that is the case, you can't use a strcmp. Instead you can do:
if(cond = (charArray[position] - *searchItem) == 0)
strcmp assumes that the strings being compared are zero-terminated, and exactly equal length. Therefore, strlen(&charArray[position]) has to equal strlen(&searchItem[counter]). That means position == strlen(&charArray[0]) - strlen(&searchItem[counter]). You don't need to search at all. Either the suffix of charArray matches or it doesn't.
But that's probably not what you intended. What are you trying to achieve?
Are the strings to be compared all of the exact same length? Your code is assuming so. If not, you'll want to use strncmp( ), not strcmp().
strcmp compares all the characters in a char* up to the trailing '\0' character. So you cannot compare single characters (basically you always need two, the character and the trailing '\0') and you cannot compare parts of a string unless you insert a '\0' at the location up to which you want to perform the comparison.
Just for clarity, properly zero terminated strings (last character is '\0') are important for strcmp. strcmp compares two character arrays from the start up to the '\0' character and returns an appropriate comparison value (<0, =0, >0). And of course, both character arrays have to be the same length.
If these are ASCII strings and should be sorted in alphabetic order, I believe it should be
else if(cond < 0){
end = position - 1;
}
else
begin = position + 1;
}
I'm not certain how you wish to sort them though?
I am learning C. And, I see this function find length of a string.
size_t strlen(const char *str)
{
size_t len = 0U;
while(*(str++)) ++len; return len;
}
Now, when does the loop exit? I am confused, since str++, always increases the pointer.
while(*(str++)) ++len;
is same as:
while(*str) {
++len;
++str;
}
is same as:
while(*str != '\0') {
++len;
++str;
}
So now you see when str points to the null char at the end of the string, the test condition fails and you stop looping.
C strings are terminated by the NUL character which has the value of 0
0 is false in C and anything else is true.
So we keep incrementing the pointer into the string and the length until we find a NUL and then return.
You need to understand two notions to grab the idea of the function :
1°) A C string is an array of characters.
2°) In C, an array variable is actually a pointer to the first case of the table.
So what strlen does ? It uses pointer arithmetics to parse the table (++ on a pointer means : next case), till it gets to the end signal ("\0").
Once *(str++) returns 0, the loop exits. This will happen when str points to the last character of the string (because strings in C are 0 terminated).
Correct, str++ increases the counter and returns the previous value. The asterisk (*) dereferences the pointer, i.e. it gives you the character value.
C strings end with a zero byte. The while loop exits when the conditional is no longer true, which means when it is zero.
So the while loop runs until it encounters a zero byte in the string.
Using just C
I would like to parse a string and:
count the occurrences of a character in a string (for example, count all the 'e's in a passed in string)
Once counted (or even as I am counting) replace the e's with 3's
OK, you're either lazy, or stuck, assuming stuck.
You need a function with a signature something like
int ReplaceCharInString(char* string, char charToFind, char charThatReplaces)
{
}
Inside the function you need
To declare an integer to count the
occurrences
A loop that moves from the start of
the string to it's end
inside the loop, an if statement to
check is the current char the
charToFind,
statements to increment the count of
occurrences and perform the
replacement
After the loop, you need to return
the count of occurrences
This function will take a string, replace every 'e' with '3', and return the number of times it performed the substitution. It's safe, it's clean, it's fast.
int e_to_three(char *s)
{
char *p;
int count = 0;
for (p = s; *p; ++p) {
if (*p == 'e') {
*p = '3';
count++;
}
}
return count;
}
Here's a shell to get you started. Ask here if you need any help.
#include <string.h>
#include <stdio.h>
int main(){
const char* string = "hello world";
char buffer[256];
int e_count = 0;
char* walker;
// Copy the string into a workable buffer
strcpy(buffer,string);
// Do the operations
for(walker=buffer;*walker;++walker){
// Use *walker to read and write the current character
}
// Print it out
printf("String was %s\nNew string is %s\nThere were %d e's\n",string,buffer,e_count);
}
In general, it's better use a standard library function rather than rolling your own. And, as it just so happens, there is a standard library function that searches a string for a character and returns a pointer to it. (It deals with a string, so look among the functions that have the prefix "str") (The library function will almost certainly be optimized to use specialized CPU opcodes for the task, that hand written code would not)
Set a temp pointer (say "ptr") to the start of the string.
In a loop, call the function above using ptr as the parameter, and setting it to the return value.
Increment a counter.
Set the character at the pointer to "3" break when 'e' is not found.
Some of you guys are starting in the middle.
A better start would be
char *string = "hello world";
Assert(ReplaceCharInString(string, 'e', '3') == 1);
Assert(strcmp(string, "h3llo world") == 0);