c - 在C中将字符串拆分为一定大小的字符串

标签 c string

假设我有一个字符串“abcd1234efgh”。我想把它分成长度为 4 的子串,比如: A B C D 1234 嗯

我的 C 生锈了。这是我写的:

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

int main(void){

int i,j;
char values[32]="abcd1234efgh";
char temp[10];

for(i=0;values[i]!='\0';){
   for (j=0;j<4;j++,i++){
      temp[i]=values[j];
      printf("%c\n",values[j]);
   }
printf("string temp:%s\n",temp);
}

return 0;
}

输出显然是错误的,因为我没有保存原始字符串的索引。有关如何解决此问题的任何提示?对于长度不是 4 的倍数的字符串,我想用空格填充短子字符串。

最佳答案

如果您只想打印,这应该可以解决问题:

int len = strlen(values);
for (int off = 0; off < len; off += 4)
    printf("%.4s\n", values+off);

如果您想(也)与 4 人一组做其他事情,那么我会考虑:

int len = strlen(values);
for (int off = 0; off < len; off += 4)
{
    strncpy(temp, values+off, 4);
    temp[4] = '\0';
    …do as you will with temp…
}

关于c - 在C中将字符串拆分为一定大小的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21084502/

相关文章:

python - 将尾随空格添加到字符串列表

c# - 每次按下按钮时,如何从字符串的前面连续移动n个字符到末尾?

C++ 字符串/字符* 连接

c - 相当于 Ctrl + Z 的 Ubuntu

c - 我如何获取存储在结构中的值?

c - makefile fatal error : no such file or directory,但文件位于当前目录

string - F# 中有用于将字符串解析为 int 的函数吗?

java - 用分隔符连接字符串

c - 如何使用 WinAPI/Win32 查找二进制文件中的序列?

c - 告诉 sscanf 将\0 视为要读取的有效字符