如何将字符串拆分为大小相等的部分并将其复制到临时字符串数组中,以便用 c 语言进一步处理



Enter String="HELLOGOODMORNING"拆分大小 = 8我想将其拆分为 8-8 大小并将其存储在 tempstring[8] 中并对其进行独立处理,然后在另外 8 个字符上相同,这些直到字符串不会结束。

#include<stdio.h>
#include<stdlib.h>
void passtofun(char string[8])
{
//logic of operation
}
void main()
{
 char caETF[8];
 char caText="HELLOGOODMORNING";//strlen will in multiple of 8.
 int i,j,len;
 len=strlen(caText);
for(i = 0; i < len; i+=8)
  {
      strncpy(caETF,caText,8);
      passtofun(caETF); 
      // passtofun() is the logic/function i want to perform on 8 char independently.
   } 
}

第一次应该采用caETF="HELLOGOO",并将其传递给passtofun(caETF)。在第二个它应该采取caETF="DMORNING",并应该把它传递给passtofun(caETF),同样地直到字符串的末尾。我已经尝试过如上所述,但它仅适用于前 8 个字符。怎么做?

你去吧!

strncpy(caETF,caText,8);修改它strncpy(caETF,caText+i,8);这将适用于任何情况。

字符串声明应该像char *Text = "HELLOGOODMORNING";而不是char caText = "HELLOGOODMORNING";

int main()
{
  char *text = "HELLOGOODMORNING"; /* string length 16, array size 17 */
  /* size of these has to accomodate the terminating null */
  char one[8];
  char two[8];

  /* copy 8 characters, starting at index 0 */
  strncpy(two, &text[0], 8);

  /* we can do strcpy if we're at the end of the string.  It will stop when it hits '' */
  strcpy(one, &text[7]);
  /* note that we still have to null-terminate the strings when we use strncpy */
  two[2] = '';

  /* but we don't have to null-terminate when we use strcpy */
  /* so we can comment this out: one[5] = ''; */
  printf("%sn", one);
  printf("%sn", two);

  return 0; /* returns 0, since no errors occurred */
}

你做的事情实际上不起作用,因为你声明的变量caText甚至不是一个字符串,而是一个字符。
我基于以下事实:您只对切入一半的字符串感兴趣,但您实际上可以通过任何其他值
修改 if

 #include <string.h>
    void main()
    {
     char caETF[8 + 1]; // +1 for ''
     char caText[]="HELLOGOODMORNING";// here you forget the [] 
     int i,j,len;
     i = 0;
     j = 1; //initialize j = 1 because i devide len by j and you cant divide by 0
     len = strlen(caText) + 1; //add 1 because j = 1
     for (j ; j < len ; j++)
      {
          if (len / j >= 2){  //if middle of string then copy in tmp string
          caETF[i] = caText[j];
          i++;
          }
       }
      caETF[i] = ''; //add '' so the computer understand that the string is terminated
      passtofun(caETF);  //now you can do whatever you want with that string
    }

caETF[i] = caText[j];允许您将字符从位置j复制到新数组中的位置i。(例如:caETF[0] = caText[9])。

最新更新