c - How to print a substring in C
问题描述
simple C question here! So I am trying to parse through a string lets say: 1234567W
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
//pointer to open file
FILE *op;
//open file of first parameter and read it "r"
op = fopen("TestCases.txt", "r");
//make an array of 1000
char x[1000];
char y[1000];
//declare variable nums as integer
int nums;
//if file is not found then exit and give error
if (!op) {
perror("Failed to open file!\n");
exit(1);
}
else {
while (fgets(x, sizeof(x), op)) {
//pounter to get the first coordinate to W
char *p = strtok(x, "W");
//print the first 3 digits of the string
printf("%.4sd\n", p);
}
}
return 0;
My output so far shows: "123d" because of the "%.4sd" in the printf function. I now need to get the next two numbers, "45". Is there a regex expression I can use that will allow me to get the next two digits of a string? I am new to C, so I was thinking more like "%(ignore the first 4 characters)(print next 2 digits)(ignore the last two digits)"
input: pic
output: pic
Please let me know. Thanks all.
解决方案
printf("Next two: %.2s\n", p + 4);
应该管用。
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int main(int argc, char *argv[]) {
//pointer to open file
FILE *op;
//open file of first parameter and read it "r"
op = fopen("TestCases.txt", "r");
//make an array of 1000
char x[1000];
char y[1000];
//declare variable nums as integer
int nums;
//if file is not found then exit and give error
if (!op) {
perror("Failed to open file!\n");
exit(1);
}
else {
while (fgets(x, sizeof(x), op)) {
//pounter to get the first coordinate to W
char *p = strtok(x, "W");
//print the first 3 digits of the string
printf("%.4sd\n", p);
printf("Next two: %.2s\n", p + 4);
}
}
return 0;
}
旁注:我添加了一个缺失stdio.h
的包含。请打开编译器警告,因为此错误会被它们捕获。
推荐阅读
- .net - requestFiltering 具有无效的子元素
- git - 几个 gitlab & svn 项目迁移到一个 gitlab 项目中
- linux - 打印所有文件名,如果有特定字符串,则在每个名称后附加 1,否则附加 0
- amazon-web-services - AWS CDK 部署到阶段而不删除之前的阶段
- python - python windows中的utf8编码问题
- c - 将 malloc 用于二叉搜索树
- sql - SQL 垂直创建记录
- scala - Deequ 检查的结果数据框的列表示什么?
- freepascal - Lazarus / Freepascal DBGrid(或 StringGrid)中的自定义控件
- flutter - 关于 StateUpdates 如何与 Riverpod 一起工作的一般问题