本文目錄一覽:
C語言里如何把已有的字元串寫入文件里?
設要寫入的數字是int型,則用控制字元串%d和%s來完成,舉例代碼行如下:
fprintf(fp,”%d %s\n”,12345,”abcdefg”);
其中:fp是成功寫打開文件的指針。此代碼行先向文件寫入整型數字12345,再加一個空格,接著寫入字元串abcdefg,然後寫入’\n’。
#include “stdio.h”
#include “string.h”
void main()
{
char a[6]=”china”;
char temp[1024];
int n=0;//記錄有多少個china
FILE *outFile=fopen(“c:\b.txt”,”r+”);
FILE *inFile=fopen(“c:\a.txt”,”r+”);
while(fgets(temp,500,inFile)!=NULL)
{
int k=0;
for(int i=0;istrlen(temp);i++)
{
if(temp[i]==a[k] kstrlen(a))
{
k++;
}
else
{
if(k==strlen(a))
{
n++;
fprintf(outFile,”%s
“,a);
}
k=0;
}
}
}
}
在C盤要有這兩個文件。。。
a文件中可能有多個china ,指定加到第幾行自己看情況 在設置一個int變數記錄就行了
c語言:如何把字元串分解為一個個的字元?
1.
不需要專門分割,c語言裡面本來就是用字元數組來保存的,如:char
a[20]=”hello
world!”;這個字元串,char[0]就是h,char[1]就是e。
2.
如果要分割子串,可以使用strtok函數。
char
*strtok(char
*s,
char
*delim);
分解字元串為一組字元串。s為要分解的字元串,delim為分隔符字元串。
首次調用時,s指向要分解的字元串,之後再次調用要把s設成null。
strtok在s中查找包含在delim中的字元並用null(”)來替換,直到找遍整個字元串。
c語言把一個字元串複製到另一個字元串
用char指針複製字元串用while循環:
#includestdio.h
int main()
{ char s[300],s1[300],*p=s,*q=s1;
gets(s);
while(*q++=*p++);
puts(s1);
return 0;
}
=================
用庫函數:
#includestdio.h
#includestring.h
int main()
{ char s[300],s1[300];
gets(s);
strcpy(s1,s);
puts(s1);
return 0;
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/238222.html