Delete space error in C programming - c

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#pragma warning(disable:4996)
#define SIZE 100
int main(void){
char str[SIZE];
char str2[SIZE];
int i;
int len;
gets(str);
len = strlen(str);
for (i = 0; str[i] != NULL; i++) {
if (str[i] != ' '){
str2[i] = str[i];
}
}
for (i = 0; i < len; i++){
printf("%c", str2[i]);
}
return 0;
}
It returns the following error:
What is the problem?
I just want to copy some elements in str to str2 without spaces, but when I run, it has got some weird letters.

You need two index variables
one to go through str
one to tell where to write next to str2
code:
len = strlen(str);
int j;
for (i=0, j=0 ; str[i] != '\0' ; i++) {
if (str[i] != ' '){
str2[j++] = str[i]; // store to str2 and increment j
}
}
Then store a final \0 to str2 at index j
str2[j] = '\0';
Finally, to print the result, you can do that one shot
printf("%s\n", str2);
instead of printing one char at a time.

For starters these headers
#include <stdlib.h>
#include <windows.h>
can be removed because neither declaration from the headers is used in the program.
The function gets is unsafe and is not supported by the C Standard any more. Instead use standard C function fgets.
When str is copied in str2 you have to use separate index to access characters in str2 because some characters from str are not copied. Otherwise the array str2 will contain gaps. As result you can not use the previous value of the variable len with the array str2.
Also it is desirable not to copy any other white space characters.
The program can look the following way
#include <stdio.h>
#include <ctype.h>
#define SIZE 100
int main(void)
{
char str[SIZE];
char str2[SIZE];
fgets( str, sizeof( str ), stdin );
const char *p = str;
char *p2 = str2;
do
{
if ( !isspace( ( unsigned char )*p ) )
{
*p2++ = *p;
}
} while ( *p++ );
for ( p2 = str2; *p2; ++p2 )
{
printf( "%c", *p2 );
}
return 0;
}
Its output might be
Hello World
HelloWorld
If you do not study yet pointers then the program can look like
#include <stdio.h>
#include <ctype.h>
#define SIZE 100
int main(void)
{
char str[SIZE];
char str2[SIZE];
fgets( str, sizeof( str ), stdin );
size_t i = 0, j = 0;
do
{
if ( !isspace( ( unsigned char )str[i] ) )
{
str2[j++] = str[i];
}
} while ( str[i++] );
for ( j = 0; str2[j]; ++j )
{
printf( "%c", str2[j] );
}
return 0;
}

Related

How to write a function in c that counts words

I had an exam yesterday in which one of the questions was about counting words in a given string.
The definition of word would be a portion of a string that is divided by spaces and/or the beginning/end of the string
I am new to C, and was not able to create a condition where it increases the counter word when you find “space (characters) space”
int count_words(char *str)
int i = 0;
int word = 2;
while (str[i])
{
if (str[i] == ‘ ‘)
{
int l = 1;
while (str[i + l]
{
l++;
}
if (l != 1)
{
word++;
}
}
}
For starters the function should be declared like
size_t count_words(const char *str);
The function parameter should be declared with the qualifier const because the passed string is not being changed within the function and the function return type should be size_t that is the same return type as for example of standard string function strlen.
It is unclear why the variable word in your function is initialized by 2
int word = 2;
Or the variable i is not being changed within the function.
The function can look the following way as shown in the demonstration program below
#include <ctype.h>
#include <string.h>
#include <stdio.h>
size_t count_words( const char *s )
{
size_t n = 0;
while ( *s )
{
while ( isspace( ( unsigned char )*s ) ) ++s;
if ( *s )
{
++n;
while ( *s && !isspace( ( unsigned char )*s ) ) ++s;
}
}
return n;
}
int main( void )
{
const char *s = "How to write a function in c that counts words";
size_t n = count_words( s );
printf( "The string \"%s\"\ncontains %zu words\n", s, n );
}
The program output is
The string "How to write a function in c that counts words"
contains 10 words
If to use as delimiters only the space character ' ' then the header <ctype.h> should be removed and the function will look like
size_t count_words( const char *s )
{
size_t n = 0;
while ( *s )
{
while ( *s == ' ' ) ++s;
if ( *s )
{
++n;
while ( *s && *s != ' ' ) ++s;
}
}
return n;
}
A more general function that can process any delimiters can look the following way
size_t count_words( const char *s, const char *delim )
{
size_t n = 0;
while (*s)
{
s += strspn( s, delim );
if (*s)
{
++n;
s += strcspn( s, delim );
}
}
return n;
}
The function has a second parameter that specifies delimiters. For example the function can be called loke
size_t n = count_words( s, " \t?!:;,." );
Try this way:
# include<stdio.h>
# include<string.h>
# define MaxBufferSize 50
void main(){
int count =0, size;
char str[MaxBufferSize+2];
printf("Enter string(max char 50 only): ");
if(fgets(str,sizeof(str), stdin)) {
if(strlen(str) > MaxBufferSize) printf("Max chars exceeded so chars before the limit were used!!!\n");
str[strcspn(str, "\n")] = '\0';
}
size = strlen(str);
int i=0;
if(size == 0) printf("Nothing entered\n");
else {
while(i<size){
while(!isalnum(str[i]) && i<size) i++;// ignores all spaces and other chars
if(str[i] == '\0') break;
while(isalnum(str[i]) && i<size) i++;// includes all words and numbers
count++;
}
printf("Words in string: %d\n",count);
}
}
hope it helps...! ;)
#include <stdio.h>
int count_words(char *str) {
int i, count=0;
int in_word = 0; // Flag to track if we're currently inside a word or not
// Loop through each character in the string
for(i=0; str[i]!='\0'; i++) {
// If current character is not a space or newline and we're not already inside a word, increment word count
if((str[i]!=' ' && str[i]!='\n') && !in_word) {
count++;
in_word = 1; // Set flag to indicate we're currently inside a word
}
// If current character is a space or newline, set flag to indicate we're not inside a word
else if(str[i]==' ' || str[i]=='\n') {
in_word = 0;
}
}
return count;
}
#include <stdio.h>
#include <string.h>
void main()
{
char s[200];
int count = 0, i;
printf("Enter the string:\n");
scanf("%[^\n]s", s);
for (i = 0;s[i] != '\0';i++)
{
if (s[i] == ' ' && s[i+1] != ' ')
count++;
}
printf("Number of words in given string are: %d\n", count + 1);
}
Use this code it will definitely works fine ):

How to print a specific character from a string in C

I'm recently practicing looping. I learned how to print: for example home to h ho hom home. by using
#include <stdio.h>
#include <string.h>
int main (){
char s[100];
printf("Input string = ");
scanf("%[^\n]", s);
for (int i=1; i<=strlen(s); i++){
for(int j = 0; j<i; j++)
printf("%c", s[j]);
printf("\n");
}
return 0;
How can i reverse it so it can be
home
hom
ho
h
instead? thank you.
It is easy to do. For example
for ( size_t i = strlen( s ); i != 0; i-- )
{
for ( size_t j = 0; j < i; j++ )
{
putchar( s[j] );
}
putchar( '\n' );
}
Another way is the following
for ( size_t i = strlen( s ); i != 0; i-- )
{
printf( ".*s\n", ( int )i, s );
}
provided that an object of the type int is able to store the length of the passed string.
Here is a demonstration program.
#include <stdio.h>
#include <string.h>
int main( void )
{
const char *s = "home";
for (size_t i = strlen( s ); i != 0; i--)
{
printf( "%.*s\n", ( int )i, s );
}
}
The program output is
home
hom
ho
h
You could loop over the string using putc, but it might also be helpful to understand the destructive approach that shortens the string and uses %s to print strings. eg:
#include <stdio.h>
#include <string.h>
int
main(int argc, char **argv)
{
char *s = argc > 1 ? argv[1] : strdup("home");
for( char *e = s + strlen(s); e > s; e -= 1 ){
*e = '\0';
printf("%s\n", s);
}
return 0;
}
Note that this approach is destructive. When complete, the string is null. As an exercise, it might be helpful to fix that.
You'll basically go backwards in your loop.
Instead of:
for (int i=1; i<=strlen(s); i++){
You'd have
for (int i=strlen(s); i>0; i--){

How to reverse every characters in words in a string in C language? [duplicate]

I have a string with the name "Mustang Sally Bob"
After i run my code i want the string output to be like this: gnatsuM yllaS boB
My approach is to count the words until the space and save the index of where the space is located in the string. then Then I want to print the characters starting from the space backwards.
#include <stdio.h>
int main()
{
char* test="Mustang Sally Bob";
int length; //string length
int x;
for(length=0;test[length] !=0&&test[length];length++); //get string length
int counter;
int words = 0;
int space_index =0;
for(counter=0;counter<length;counter++) {
words++;
if(test[counter]==' ') {
space_index=counter;
for(x=space_index-1;x>=words;x--) {
printf("%c",test[x]);
}
words=0;
space_index = 0;
}
}
return 0;
}
but when I execute this code the output I get is yllaS g
does anyone know why i cant get the full string?
In general the approach is incorrect.
For example an arbitrary string can start with blanks. In this case the leading blanks will not be outputted.
The last word is ignored if after it there is no blank.
The variable words does not keep the position where a word starts.
Calculating the length of a string with this loop
for(length=0;test[length] !=0&&test[length];length++);
that can be written simpler like
for ( length = 0; test[length] != '\0' ; length++ );
is redundant. You always can rely on the fact that strings are terminated by the zero-terminating character '\0'.
I can suggest the following solution
#include <stdio.h>
int main( void )
{
const char *test = "Mustang Sally Bob";
for ( size_t i = 0; test[i] != '\0'; )
{
while ( test[i] == ' ' ) putchar( test[i++] );
size_t j = i;
while ( test[i] != '\0' && test[i] != ' ' ) i++;
for ( size_t k = i; k != j; ) putchar( test[--k] );
}
return 0;
}
The program output is
gnatsuM yllaS boB
You could append the program with a check of the tab character '\t' if you like. In C there is the standard C function isblank that performs such a check.
Here is a demonstrative program that uses the function isblank. I also changed the original string literal.
#include <stdio.h>
#include <ctype.h>
int main( void )
{
const char *test = " Mustang\tSally\tBob ";
puts( test );
for ( size_t i = 0; test[i] != '\0'; )
{
while ( isblank( ( unsigned char )test[i] ) ) putchar( test[i++] );
size_t j = i;
while ( test[i] != '\0' && !isblank( ( unsigned char)test[i] ) ) i++;
for ( size_t k = i; k != j; ) putchar( test[--k] );
}
putchar( '\n' );
return 0;
}
The program output is
Mustang Sally Bob
gnatsuM yllaS boB

reversing only certain words of a string

I have a string with the name "Mustang Sally Bob"
After i run my code i want the string output to be like this: gnatsuM yllaS boB
My approach is to count the words until the space and save the index of where the space is located in the string. then Then I want to print the characters starting from the space backwards.
#include <stdio.h>
int main()
{
char* test="Mustang Sally Bob";
int length; //string length
int x;
for(length=0;test[length] !=0&&test[length];length++); //get string length
int counter;
int words = 0;
int space_index =0;
for(counter=0;counter<length;counter++) {
words++;
if(test[counter]==' ') {
space_index=counter;
for(x=space_index-1;x>=words;x--) {
printf("%c",test[x]);
}
words=0;
space_index = 0;
}
}
return 0;
}
but when I execute this code the output I get is yllaS g
does anyone know why i cant get the full string?
In general the approach is incorrect.
For example an arbitrary string can start with blanks. In this case the leading blanks will not be outputted.
The last word is ignored if after it there is no blank.
The variable words does not keep the position where a word starts.
Calculating the length of a string with this loop
for(length=0;test[length] !=0&&test[length];length++);
that can be written simpler like
for ( length = 0; test[length] != '\0' ; length++ );
is redundant. You always can rely on the fact that strings are terminated by the zero-terminating character '\0'.
I can suggest the following solution
#include <stdio.h>
int main( void )
{
const char *test = "Mustang Sally Bob";
for ( size_t i = 0; test[i] != '\0'; )
{
while ( test[i] == ' ' ) putchar( test[i++] );
size_t j = i;
while ( test[i] != '\0' && test[i] != ' ' ) i++;
for ( size_t k = i; k != j; ) putchar( test[--k] );
}
return 0;
}
The program output is
gnatsuM yllaS boB
You could append the program with a check of the tab character '\t' if you like. In C there is the standard C function isblank that performs such a check.
Here is a demonstrative program that uses the function isblank. I also changed the original string literal.
#include <stdio.h>
#include <ctype.h>
int main( void )
{
const char *test = " Mustang\tSally\tBob ";
puts( test );
for ( size_t i = 0; test[i] != '\0'; )
{
while ( isblank( ( unsigned char )test[i] ) ) putchar( test[i++] );
size_t j = i;
while ( test[i] != '\0' && !isblank( ( unsigned char)test[i] ) ) i++;
for ( size_t k = i; k != j; ) putchar( test[--k] );
}
putchar( '\n' );
return 0;
}
The program output is
Mustang Sally Bob
gnatsuM yllaS boB

Splitting a string into chunks.

I'm trying to split a string into chunks of 6 using C and I'm having a rough time of it. If you input a 12 character long string it just prints two unusual characters.
#include <stdio.h>
#include <string.h>
void stringSplit(char string[50])
{
int counter = 0;
char chunk[7];
for (unsigned int i = 0; i < strlen(string); i++)
{
if (string[i] == ' ')
{
continue;
}
int lastElement = strlen(chunk) - 1;
chunk[lastElement] = string[i];
counter++;
if (counter == 6)
{
printf(chunk);
memset(chunk, '\0', sizeof chunk);
counter = 0;
}
}
if (chunk != NULL)
{
printf(chunk);
}
}
int main()
{
char string[50];
printf("Input string. \n");
fgets(string, 50, stdin);
stringSplit(string);
return(0);
}
I appreciate any help.
Your problem is at
int lastElement = strlen(chunk) - 1;
Firstly, strlen counts the number of characters up to the NUL character. Your array is initially uninitialized, so this might cause problems.
Assuming your array is filled with NULs, and you have, let's say, 2 characters at the beginning and you are looking to place the third one. Remember that your 2 characters are at positions 0 and 1, respectively. So, strlen will return 2 (your string has 2 characters), you subtract one, so the lastElement variable has the value 1 now. And you place the third character at index 1, thus overwriting the second character you already had.
Also, this is extremely inefficient, since you compute the number of characters each time. But wait, you already know how many characters you have (you count them in counter, don't you?). So why not use counter to compute the index where the new character should be placed? (be careful not to do the same mistake and overwrite something else).
The function is wrong.
This statement
int lastElement = strlen(chunk) - 1;
can result in undefined behavior of the function because firstly the array chunk is not initially initialized
char chunk[7];
and secondly after this statement
memset(chunk, '\0', sizeof chunk);
the value of the variable lastElement will be equal to -1.
This if statement
if (chunk != NULL)
{
printf(chunk);
}
does not make sense because the address of the first character of the array chunk is always unequal to NULL.
It seems that what you mean is the following.
#include <stdio.h>
#include <ctype.h>
void stringSplit( const char s[] )
{
const size_t N = 6;
char chunk[N + 1];
size_t i = 0;
for ( ; *s; ++s )
{
if ( !isspace( ( unsigned char )*s ) )
{
chunk[i++] = *s;
if ( i == N )
{
chunk[i] = '\0';
i = 0;
puts( chunk );
}
}
}
if ( i != 0 )
{
chunk[i] = '\0';
puts( chunk );
}
}
int main(void)
{
char s[] = " You and I are beginners in C ";
stringSplit( s );
}
The program output is
Youand
Iarebe
ginner
sinC
You can modify the function such a way that the length of the chunk was specified as a function parameter.
For example
#include <stdio.h>
#include <ctype.h>
void stringSplit( const char s[], size_t n )
{
if ( n )
{
char chunk[n + 1];
size_t i = 0;
for ( ; *s; ++s )
{
if ( !isspace( ( unsigned char )*s ) )
{
chunk[i++] = *s;
if ( i == n )
{
chunk[i] = '\0';
i = 0;
puts( chunk );
}
}
}
if ( i != 0 )
{
chunk[i] = '\0';
puts( chunk );
}
}
}
int main(void)
{
char s[] = " You and I are beginners in C ";
for ( size_t i = 3; i < 10; i++ )
{
stringSplit( s, i );
puts( "" );
}
}
The program output will be
You
and
Iar
ebe
gin
ner
sin
C
Youa
ndIa
rebe
ginn
ersi
nC
Youan
dIare
begin
nersi
nC
Youand
Iarebe
ginner
sinC
YouandI
arebegi
nnersin
C
YouandIa
rebeginn
ersinC
YouandIar
ebeginner
sinC

Resources