用字符串的一部分填充二维数组 [英] fill two dimensional array with parts of a string

查看:71
本文介绍了用字符串的一部分填充二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望将我断开的字符串部分输入到二维数组中,例如:
字符串:一天
数组中的结果:Col1:一个Col2:day

I want the parts of the string I broke to be entered to a two-dimensional array, for example: String: "one day" Result in array: Col1: one Col2: day

问题是,如何用列1和<$ c $的两个变量 result2 填充数组c> result 第2列?

The question is, how do I fill the array with those two variables result2 for column 1 and result for column 2?

到目前为止,这是我的代码(如您所见,我有一个单独的历史记录数组和一个单独的数组用于保存用户输入内容的数组):

This is my code so far(as you can see i have a separate array for history and a separate array for holding the parts of the user input):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (int argc, char *argv[])
{
    int i=0; int j=0; int k=0;
    char inputString[100];
    char *result=NULL;
    char *result2=NULL;
    char delims[] = " ";
    char historyArray[100][100] = {0};
    char historyKey[] = "history";
    char *tokenArray[100][100] = {0} ;
    //char exitString[] = "exit";

    do
    {

             printf("hshell>");
             gets(inputString);
             strcpy (historyArray[k], inputString);
             k++;


             // Break the string into parts
             result = strtok(inputString, delims);

             while (result!=NULL)
             {
                   result2 = result;
                  puts(result);
                  result= strtok(NULL, delims);
                  for (int count = 0; count < k; count++)
                    tokenArray[count] = result2;
                  j++;
             }



              if (strcmp(inputString,historyKey) == 0) 
                {
                    for (i=0; i<k; i++)
                    {
                        printf("%d. %s \n",i+1,historyArray[i]);
                    }
                }  
                else if (strcmp ("exit",inputString) != 0)
                {
                    printf("\nCommand not found \n");
                }

    }while (strcmp ("exit", inputString) != 0);
    return 0;
}


推荐答案

首先,听起来像你需要一维数组作为输入:

First, it sounds like you need a single dimensional array for input:

  char tokenArray[100];

然后再往下走,循环将执行此操作:

Then farther down, the loop would do this:

result = strtok(inputString, delims);

j = 0;
while (result!=NULL)
{
    strcpy(tokenArray[j++], result);
    puts(result);
    result= strtok(NULL, delims);
}

尝试使用该提示并查看其余内容。

Try with that hint and see about the rest.

这篇关于用字符串的一部分填充二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆