Using C to remove certain characters then put rest in array - c

How can I take a string (in this case it'll be loaded from a file) then remove certain characters and store them in an array.
Ex:
f.e.d.r.t.g.f
remove "." to get f e d r t g f in an array where I can manipulate each individually

Just iterate through the string and only copy the characters you're interested in, maintaining an index of the current position in the new array.

strtok() does this easily if
the code is used in a single thread
You don't mind if the source string is changed in the process.

You can loop over them, if the character is rejected go to next character (or return if no more chacters). If it is not rejected push it into the array. That would create a copy of the characters, but unless your string is gigantic it is not a problem. If it is, my answer wont suffice :)
Another variant would be a function that reads the string until it hits a valid character and returns it. To get the next character call the function again. The function needs to maintain an index variable passed to it though. If the end of the string is reached you would need to indicate it somehow.

Related

Finding a string in a file [C]

Could anyone tell me the way how to find string (which you enter in a program) in a .txt file without using function for that?(Just need an algorithm for that nothing else) EXAMPLE: i have file named NAMES.txt with surnames on the first line separate with space like that:
John Peter Paul
and in my program I enter name for example Paul and it finds it in that file and write "the name is there"
name = Paul;
I have one method on my mind that if i enter for example Paul to my program it would scan all chars one by one in that file in a row and if name[1] = P then it would start scaning and comparing letters and if they were the same it would each time increase counter p by one (p++) and if p = lenghth of name then the name would be there (there might be 1 bug which comes to my mind that if you enter Paul and in the file theres name Paula it will actually write "The name is there" if i used that method but it should not be impossible to debug)
Could anyone also tell me if my written method is possible to realize ?
I suggest avoiding reading the entire file into memory. Large files might result in large memory consumption, which is far from ideal.
Presumably you have the string to search for in memory somewhere; it's already in an allocation. Create another allocation of the size of that string, and read that many bytes into it... Don't forget to account for the '\0' string terminator.
Check to see if it matches. If the string matches, well, obviously you've found a match within that file. If it doesn't, shift the array one byte left, read another byte onto the end of it. Rinse, lather, repeat until you find a match.
The bug you mentioned implies that you need a string terminator, in the file, somewhere. Technically speaking, a string terminator is a '\0', but you could substitute any terminal value(s). Just replace the value(s) you choose (perhaps whitespace?) with a '\0' as you're reading.
Function fgets() will be useful for this task as you can store whole string in buffer instead of one character at a time .
fgets(name,100,fp)
Where name is string pointer where string read is stored ,100 is the number of characters to be read and fp is the FILE pointer from where you want to read.
And then you can use function strcmp() to compare the string and name you want to search .So it will eliminate the other possibility of matching with a different name.

Searching for a combination of characters in a file

I am trying to create a program that reads a file and searches for a specific combination of characters.
For example: "/start/ 4jy42jygsfsf /end/".
So I want to find all the "strings" starting with /start/ and ending with /end/.
In order to do that, I use read() function because the file might be a binary file (it doesn't have to be a file with chars).
I call the read() function like that:
#define BUFFSIZE 4000
// more declarations
while (read(file_descriptor, buffer, BUFFSIZE) > 0)
{
//search for /start/
//then search for /end/
//build a string with all the chars between these two
//keep searching till you reach the end of buffer
}
Assume that every /start/ is followed by an /end/.
The question is:
How do I deal with cases that this combination of characters is cut in half?
For example, let's say that the first time read() gets called, in the end of this buffer I spot /star and the next time read() gets called at the start of the second buffer there is t/ 4jy42jygsfsf /end/.
This combination might get cut anywhere. The solutions I thought will result to many many lines of code. Is there any smart way to deal with all these cases?
When you reach the end of the buffer, record the state of the current partial match, if any. Then when you get the next buffer, you have 4 general cases:
Not inside any text to be matched.
Saw just a beginning / at the end of the last buffer
Currently inside /start/. Another variable records how far you have matched.
Currently inside /end/. Same variable as for /start/ records how far you have matched.
Your states inside the matcher are generally:
Currently not matching anything
Just saw a / - next looking for an 's' or an 'e'.
Matching either start/ or end/.
Matched - either /start or /end.
Based on the partial match, just jump to the right state in the matcher.
OR
You can use the PCRE library. It supports partial matching. But probably is overkill for your purposes.

Trimming a char array in C

I am working on an assignment and I have been noticing a problem in my coding assignment. It is not clear to me how to tackle this problem, probably due to a lack of sleep but anyway. I need to trim a char array of it's white spaces for this assignment.
The solution I thought of involved a second char array and just simply copy the non white spaces to that array and I'm done. But how can I create a char array without knowing it's size, because at that moment I do not yet know the size. I still need to trim it in order to know how many characters need to be copied to the new array, which varies in the assignment
I know there are a lot of good questions out here on stackoverflow but I think this has more to do with the thought process rather then the correct syntax.
My second problem is how do I perform a fscanf/fgetc on a char array since it needs a stream, is it sufficient to give it a pointer rather then a stream?
If making the change in-place simply, shift every chracter after a space back, and repeat till the end of the array. This is very inefficient.
If making a new copy, make a new array of the same length, and then do as you were doing (copy all the non-space characters). If you copy the \0 character as well, then there will be no string termination issue. This is much more efficient.
Going by your comments, it appears you may have the option to input the array in any form you wish. I would then recommend that instead of doing text manipulations later on, just input the string in the form you need.
You can simply use scanf or fscanf repeatedly, to input the separate words into the same array. This will take care of all the whitespaces.
Here is one partial idea: You can make a first pass on the char array and count the blanks, then take the string length minus the blanks for the second array, then perform your copy across skipping the blanks.
You could also create a pass through the array:
Test until end of array:
Is my (Current/Index) position blank? (A space)
If so, grab next available non-blank value and put it there.
then index++
If not, index++
Not sure on the second, will do some checking and see if I can find a good answer there too.

What happens when a string contains only '\0'? C

In my program I'm reading words from a .txt file and I will be inserting them into both a linked list and a hash table.
If two '\n' characters are read in a row after a word then the second word the program will read will be '\n', however I then overwrite it with '\0', so essentially the string contains only '\0'.
Is it worth me putting an if statement so the next part of my program only executes if the word is a real word (i.e. word[0] != '\n')? Would the string '\0' use up space in the hash table/linked list?
In C a character array with first element being \0 is an empty string, i.e. of length zero. There's not much sense in keeping empty strings in containers, if that's what you are asking.
It depends if you consider an empty string a valid entry. You seem to be storing words so I would guess that an empty string is of no interest, but that is application specific.
For example, an environment variable can be present (getenv returns a valid pointer) but the value can be "unset": an empty string. In that case the fact that the value is an empty string might be significant.
So, if an empty string is not significant is it worth adding an if statement to ignore it? Generally that would be a "yes", since the overhead of storing and maintaining the empty string could be significantly more than one if statement per entry. But of course that is only a guess, I don't know what your overheads are, how many times that if would get executed, and how many empty string entries you would be saving. You might not know that either, so my fallback position would be only to store data that is significant.

Remove spaces from a string, but not at the beginning or end

I am trying to remove spaces from a string in C, not from the end, nor the beginning, just multiple spaces in a string
For example
hello everyone this is a test
has two spaces between hello and everyone, and five spaces from this to is. Ultimately I would want to remove 1 space from the 2 and 4 from the 5, so every gap has 1 space exactly. Make sense?
This is what I was going to do:
create a pointer, point it to the string at element 1 char[0].
do a for loop through the length of the string
then my logic is, if my pointer at [i] is a space and my pointer at element [i+1] space then to do something
I am not quite sure what would be a good solution from here, bearing in mind I won't be using any pre-built functions. Does anyone have any ideas?
One way is to do it in-place. Loop through the string from the beginning to end. store a write pointer and a read pointer. Each loop the write pointer and read pointer advances by one. When you encounter a space transfer it as normal but then loop the read pointer incrementing each time until a non-space is found (Or the end of the string, obviously). Don't forget to add a '\0' at the end and you now have the same string without the spaces.
Are you allowed to use extra memory to create a duplicate of the string or you need to do the processing in place?
The easiest will be to allocate memory equally to the size of the original string and copy all characters there. If you meet an extra space, do not copy it.
If you need to do it in place, then create two pointers. One pointing to the character being read and one to the character being copied. When you meet an extra space, then adapt the 'read' pointer to point to the next non space character. Copy to the write position the character pointed by the read character. Then advance the read pointer to the character after the character being copied. The write pointer is incremented by one, whenever a copy is performed.
Example:
write
V
xxxx_xxxx__xxx
^
Read
A hard part here is that you can not remove an element from the array of characters easily. You could of course make a function that returns a char[] that has one particular element removed. Another option is to make an extra array that indicates which characters you should keep and afterward go over the char[] one more time only copying the characters you want to keep.
This is based on what Goz said, but I think he had finger trouble, because I'm pretty sure what he described would strip out all spaces (not just the second onwards of each run).
EDIT - oops - wrong about Goz, though the "extra one" wording would only cover runs of two spaces correctly.
EDIT - oops - pre-written solution removed...
The general idea, though, is to use the "from" and "to" pointers as others did, but also to preserve some information (state) from one iteration to the next so that you can decide whether you're in a run of spaces already or not.
You could do a find and replace for "  " and " ", and keep doing it until no more matches are found. Innefficient, but logical.

Resources