Traversing a string in C

Hello everyone,
If you could show me how to traverse a string in C.
Thank you
Configuration: Windows Vista Internet Explorer 7.0

1 answer

  • Votes
  • Date
  • Descending date
  1. Contributor
    Good evening
     char chaine[] = "Hello!"; int iterateur=0; while(chaine[iterateur] != '\0') { //In C, the character \0 corresponds to the end of your string //Put your code here iterateur++; } 


    Best regards,
    1. ```c Thank you MARCO
      Actually, I have a function "get_word" that should return the words from the string separated by a space

      Here’s what I’ve done: is this how you do it when the function returns a string type?
      Help pliz
      Thank you

      char * getword (char[50] line)
      {
      char word [50];
      for(int j=0, j< strlen(line); j++){
      if(substr(line, 1, i)=="")
      word =substr(line, 1, i);
      }
      return word
      } ```
    2. Contributor
      @célineHi,
      You don't need to complicate your life that much. If you're allowed to modify the input string, you can do this:
       char * getword (char[50] chaine) { for(int j=0; j<strlen(chaine); j++){ if(chaine[j]==' ') chaine[j]=','; } return chaine; } 


      On the other hand, if you're not allowed to modify it, I recommend creating a char* of the same size as your input string, going through the string character by character and copying each character into your new string one by one (except when you read a space, in which case you write a comma). It's better than using strcpy (which will go through your string), then going through it again to replace the spaces with commas.
    3. @Marco la baraqueTHANK YOU MARCO,
      I don't need to add commas,
      I just have to extract the words to put them into linked lists afterwards.
      thank you

      here's what I've done:
      void getword (char chaine[50])
      {
      int i=0;
      while(chaine[i]!="")
      i++;

      word=substr(ligne, 0,i);
      }

      I only have this error: incompatible types in assignments in the last instruction
      thank you
      I’m waiting for your response
    4. Contributor
      @célineOh yes, indeed, I have been stuck on the first question. I'll take a look at that and get back to you quickly.