Removing spaces in a char array [duplicate] - c

This question already has answers here:
Function to remove spaces from string/char array in C
(6 answers)
Closed 3 years ago.
I want to remove spaces from an array and rearrange the values of the array.
array[]="1 2 6 9 5";
I want the values of array like
array[]="12695"

There are tons of ways to whip up a simple solution to remove spaces from a string. Here's a little example I came up with using pointer iteration:
void remove_spaces(char * str){
char * back = str;
do{
if(*back != ' ')
*str++ = *back;
}while(*back++ != '\0');
}
This code uses two pointers to iterate across the given string. At each step of the loop, the back pointer is checked against the null character (to see if the end of the string has been reached) and incremented. In the body of the loop, the value from the back pointer is copied into the front pointer whenever back is not pointing to a ' '. str is also incremented right after this copy from *back to *str is made, using the post-increment (++) operator.

Related

String to array elements in C [duplicate]

This question already has answers here:
Split string with delimiters in C
(25 answers)
Why no split function in C? [closed]
(1 answer)
Closed 3 months ago.
I need a function that works in C like split(' ') in python. I have to add words from a string as array elements (so I have to "cut" the string at every space characters and put the words in an array). I have no idea how to do it simply.
I tried for example the strstr() but it's just find the first space in the sentence, but I have 3 spaces.
strtok
"String tokenize"
int main ()
{
char str[] ="one two three";
char * word;
word = strtok (str," ");
while (word != NULL)
{
printf ("%s\n",word);
word = strtok (NULL, " ");
}
return 0;
}
Be careful though, it modifies the input string. It replaces any "delimiter" chars with \0s.
It's also non-reentrant. It keeps state in some global variable so you can't interweave tokenizations of 2 different strings, not even talking about multi-threading.

How to extract the first X characters of a string and use them into another in C [duplicate]

This question already has answers here:
How should character arrays be used as strings?
(4 answers)
Closed 3 years ago.
I have made this function to extract the first 2 characters of a string:
string get_salt(string hash)
{
char pre_salt[2];
for (int i = 0; i < 2; i++)
{
pre_salt[i] = hash[i];
}
string salt = pre_salt;
printf("%s\n", salt);
return(salt);
}
But when I run it with a string that has "50" (is the example I'm using) as the first 2 characters, I get this output:
50r®B
And to be honest I have no idea why is it adding the 3 extra characters to the resulting string.
You are missing the string's NUL terminator '\0' so it keeps printing until it finds one.
Declare it like:
char pre_salt[3]={0,0,0};
And problem solved.

How to count how many different letters are in one text string? [duplicate]

This question already has answers here:
Count the number of occurrences of each letter in string
(15 answers)
How to count how many different vowels are in one word from text file in C?
(2 answers)
Closed 8 years ago.
How to count how many different letters are in one text string ?
It's quite trivial, actually: you only have to keep track of which characters have already been encountered in the string.
const char *str = "foo bar baz quirk qux";
bool found[1 << CHAR_BIT] = { 0 };
int n_distinct = 0;
for (const char *p = str; *p; p++) {
unsigned char ch = *p;
if (!found[ch]) {
n_distinct++;
found[ch] = 1;
}
}
printf("Distinct characters: %d\n", n_distinct);
Create a char array called uniqueLetters and a char called currentLetter.Create a for loop that sets currentLetter to each character in the string one by one. Nest another for loop inside of the first loop I described that checks if currentLetter is in the uniqueLetters array. If it is not in the uniqueLetters array add it to the uniqueLetters array. At the end count the length of the uniqueLetters array.
One thing to keep in mind is that 's' and 'S' are considered different characters. If you want to count them as the same letters you will need to add additional logic to check if either the lowercase or uppercase version of the letter exists in the uniqueLetter array.
Hope this helps!

Can someone explain this C code? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Can someone explain this reverse sentence code for me? How does the first and the second looping works? What's the point of each of them?
main(){
char arr[255], *p;
printf("Enter string: ");
gets(arr);
for(p=arr; *p!='\0'; p++);
for(p--; p>=arr; p--){
printf("%c",*p);
}
}
Input:
I love you
Output:
uoy evol I
The code is basically printing in reverse the input array.
for(p=arr; *p!='\0'; p++);
Sets p as the last (relevant) element of the array (the null character)
for(p--; p>=arr; p--){
printf("%c",*p);
}
starts from the last (none null) character and prints each one from last to first.
Question for you:
What happens if the input array is longet than 255 chars? (answer below)
buffer overflow
Suppose the input is Hello World. This gets stored in your buffer arr as
[H][e][l][l][o][ ][W][o][r][l][d][\0]...
Your pointer is set to arr, hence the pointer points to H
[H][e][l][l][o][ ][W][o][r][l][d][\0]...
^
|
p
The first loop advances (p++) until it meets the first null character (\0). It now looks like
[H][e][l][l][o][ ][W][o][r][l][d][\0]...
^
|
p
Now the second loop goes back (p--) until it reaches the first character again (actually, until the pointer equals the pointer to the beginning of the array), printing each character as it meets it. The first character \0 however is ignored with the little p-- here:
for(p--; p>=arr; p--)
^^^
The code looks clever, but it actually exhibits undefined behavior, which means the code may do anything.
The problem is the second loop:
for(p--; p>=arr; p--){
printf("%c",*p);
}
What it's intended to do is to start p at the last character of the string (excluding the terminating \0, then keep decrementing it until all the characters of the string have been output in reverse order.
The problem is the termination condition: after the intended end of the loop, p is arr, and then p-- subtracts one, and then p >= arr is false.
Unfortunately, an arithmetic operation on pointers may not result in a pointer that no longer points to the object (or one after the final object of an array), or it's undefined behavior.
That's what's happening here: p-- causes p to be off the array, and all bets are off as to what happens next.
Here's a correct way to write the second loop:
for (int i = (p-arr)-1; i >= 0; i--) {
printf("%c", p[i]);
}
I'd probably write the entire code using indexes to completely avoid pointer arithmetic. Maybe something like this:
int i = 0;
// Find the terminating \0 byte
while(p[i])i++;
// Iterate backwards through the string, outputting characters along the way.
while(--i >= 0)putc(p[i]);
Before explaining the code, I must say two things - first, the signature of the main function should be one of the following -
int main(void);
int main(int argc, char *argv[]);
and second, do not use gets. It's not safe to use. Use fgets instead. Now, coming to the code.
for(p = arr; *p != '\0'; p++) ;
In the above loop, p is assigned the base address of the array arr, i.e., the address of the first element of the array arr. The array arr contains a terminating null byte which means it is a string. The loop body is the null statement ; which means p is incremented till the null byte is encountered, i.e., when the test *p != '\0' fails. In the for loop
for(p--; p >= arr; p--) {
printf("%c",*p);
}
p is first decremented to point to the last character just before the null byte and then it is printed in each iteration till the condition p >= arr is true, i.e., till the first element of the array is reached. You should change your code to -
#include <stdio.h>
int main(void) {
char arr[255], *p;
printf("Enter string:\n");
fgets(arr, sizeof arr, stdin);
for(p = arr; *p! = '\0'; p++)
; // the null statement
for(p--; p >= arr; p--)
printf("%c", *p);
return 0;
}

Concatenating strings (2) [duplicate]

This question already has answers here:
How do I concatenate two strings in C?
(12 answers)
Closed 8 years ago.
char *val1 = "/root";
char *val2 = "/p";
val1 = val1+val2;
I want to add 2 char pointer value and assign it to 1st value. above is the code snippt.
It can't be done that way. Since you have two pointers, trying to add them will try to add the pointers themselves, not manipulate what they point at. To concatenate the two strings, you need to have/allocate a single buffer large enough to hold both:
char *both = malloc(strlen(val1) + strlen(val2) + 1);
if (both != NULL) {
strcpy(both, val1);
strcat(both, val2);
}
Use strcat or strncat functions to concatenate strings. C has no string concatenation operator.

Resources