How to get char from string

Viewed 119

Can I ask why it shows me "Zero" instead of index?

Current output: 0

Expected output: 6

#include<stdio.h>
#include<stdlib.h>
int main() {
    int index_equal;    
    char array[20] = {"2n+n2n=n4n"};
    for (int j = 0; j > 20; j++) {
        if (array[j] == '=') {
            index_equal = j;
        }
    }
    printf("\n%d", index_equal);
}
5 Answers

There is problem in for loop you should write j<20 other wise loop will never execute

for(int j=0;j<20;j++)

This should be right approach

1)problem is here

  for(int j = 0; j>20; j++)

j>20 it should be j<20.

2)And there is no need to run the loop for 20 elements instead do this

  int len=strlen(array);

and

  for(int j = 0; j<len; j++)

or

  for(int j = 0; j<10; j++)

or

   for(int j=0;array[j];j++)

3)Can I ask why it shows me "Zero" instead of index?

  for (int j = 0; j > 20; j++) 

because value of j is 0 and j > 20 is false i.e (0>20) so the loop does not execute and it prints uninitialized value(index_equal).

J>20 must be j<20 for loop doesnt execute

Solution seems to be misjudged for loop. I am providing enhancement to your code. You can use size_t to make your program more dynamic so that it can calculate size of character array and passing that in your loop.

#include<stdio.h>
#include<stdlib.h>
int main() {
    int index_equal;    
    char array[20] = {"2n+n2n=n4n"};
    size_t n = sizeof(array)/sizeof(array[0]);

    for (int j = 0; j < n; j++) {
        if (array[j] == '=') {
            index_equal = j;
        }
    }
    printf("\n%d", index_equal);
}

how can i "transfer" all these spaces into char 'n' ?

   #include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
int main()
{
    char array[10];
    for(int i = 0; i < 10; i++)
    {
    scanf("%c",&array[i]);  
    }
    int len = strlen(array);
    printf("\nLength of this array is %d\n",len);
    //make from space -->'n'
    for(int i = 0; i < 10; i++)
    {
        if(isspace(array[i])==true) // otherwise if(array[i]==' ')..
        {
            array[i]=='n';
        }
    }
    puts(array);
    return 0;
}

now i am pretty sure that my loop is in correct format

Related