开发者

Basic C Array function

开发者 https://www.devze.com 2023-02-07 12:02 出处:网络
I am new here and programming. I need to write a function to be able to divide a sentence through the desired input and output them separately.

I am new here and programming. I need to write a function to be able to divide a sentence through the desired input and output them separately.

Such as t开发者_StackOverflow中文版he input is "Hello, How are you..." it's 23 characters and the other input is numerical "6".

Thus, I want to print it as "Hello," and "How are you..."

I think it would be best to use arrays... However, I cannot write the function. I hope someone could help me..

By the way, if I wanted place the function in a header file, how can I manage that.

Thanks a lot...


First the header file that declares the split_string function. (As you are new to programming, I put detailed comments):

/* Always begin a header file with the "Include guard" so that
   multiple inclusions of the same header file by different source files
   will not cause "duplicate definition" errors at compile time. */ 
#ifndef _SPLIT_STRING_H_  
#define _SPLIT_STRING_H_

/* Prints the string `s` on two lines by inserting the newline at `split_at`.
void split_string (const char* s, int split_at);

#endif

The following C file makes use of split_string:

// test.c

#include <stdio.h>
#include <string.h> /* for strlen */
#include <stdlib.h> /* for atoi */
#include "split_string.h"

int main (int argc, char** argv)
{
  /* Pass the first and second commandline arguments to
     split_string. Note that the second argument is converted to an 
     int by passing it to atoi. */
  split_string (argv[1], atoi (argv[2]));
  return 0;
}

void split_string (const char* s, int split_at)
{
  size_t i;
  int j = 0;
  size_t len = strlen (s);

  for (i = 0; i < len; ++i)
    {
      /* If j has reached split_at, print a newline, i.e split the string.
         Otherwise increment j, only if it is >= 0. Thus we can make sure 
         that the newline printed only once by setting j to -1. */
      if (j >= split_at)
        {
          printf ("\n");
          j = -1;
        }
      else 
        {
          if (j >= 0)
            ++j;
        }
      printf ("%c", s[i]);
    }
}

You can compile and run the program as (assuming you are using the GNU C Compiler):

$ gcc -o test test.c
$ ./test "hello world" 5
hello
 world


First of all string in C is a char * which is an array of char already:

char *msg = "Hello, World!";
int i;
for(i=0; i<strlen(msg); ++i)
{
    char c = msg[i];
    // Do something
}

If you want to put your function in the header file just define it as inline

0

精彩评论

暂无评论...
验证码 换一张
取 消