C 常用的输入输出 栈 哈希 文件写读 实现 字符串处理

#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>  //引用动态分配数组的malloc

typedef struct stack
{
 int top;
 char str[10] ;
 stack * next;
}SqStack;

SqStack *  InitStack()
{
    SqStack * ret = NULL;
 ret = (SqStack*)malloc(sizeof(SqStack));
 if (ret)
 {
  /*将栈的长度初始化为0*/
  ret -> top = 0;
 }
 return ret;
}

typedef struct HashNode
{
   char data[20];
   int count;
   HashNode * next;
};


//哈希表
HashNode HashTable[100];
// 最简单hash函数  `
int hash_function( char const *p) 

    int value = 0; 
    while (*p != '/0') 
    { 
        value = value * 31 + *p++; 
        value = value % 100; 
    } 
    return value; 

//hash增加节点,对冲突使用链地址法解决
// 添加单词到hash表 
void append_word(char const *str) 
{
int index=hash_function(str);
HashNode hn = HashTable[index];
while(hn != NULL)
{
  if(strcmp(str,hn.data)==0)
  {
     hn.count++;
     return;
  }
  hn=hn.next;
}
  //新建一个节点
  HashNode nhn=new HashNode;
  nhn.count=1;
  nhn.data=new char[strlen(str)+1];
  nhn.next=HashTable[index];
 
  HashTable[index]=nhn;
}

 
int main()
{
 //哈希表

    char * str_hs="213";
 append_word(str_hs);


 //new malloc 不同 
 //malloc 和 new 至少有两个不同: new 返回指定类型的指针,并且可以自动计算所需要大小;new 自动进行初始化,malloc是随机的;new 是关键字,malloc不是;
 //malloc 释放需要判断释放null,new则不需要

 SqStack* ss1=new SqStack;
 delete(ss1);

 SqStack* ss2=(SqStack*)malloc(sizeof(SqStack));
 free(ss2);


 //栈实现
 SqStack * ss;
 ss=InitStack();
 

 //字符串处理
 
   //长度 返回值是字符串s的长度。不包括结束符'/0'。一个汉字占两个字节
 char * str1="12 e43字";//print 8
 int len= strlen(str1);
 printf("%d",len);

 char * str_1="1232";
 char * str_2="2313";
 int boolValue=strcmp(str_1,str_2);//0为相同
 getchar();

 //写文件,覆盖写
 FILE * fp_w=fopen("b.txt","w");
 FILE * fp_r2=fopen("a.txt","r");
 char tmp3[15];
 int tmp4;
 while(fscanf(fp_r2,"%s %d",tmp3,&tmp4)!=EOF)
 {
   fprintf(fp_w,"%s %d ",tmp3,tmp4);
 }
 fclose(fp_r2);
 fclose(fp_w);

 //读文件
 FILE * fp_r=fopen("a.txt","r");
 char tmp1[15];
 int tmp2;
 while(fscanf(fp_r,"%s %d",tmp1,&tmp2)!=EOF)
 {
   printf("%s",tmp1);
   printf("%d ",tmp2);
 }
 fclose(fp_r);

 //输入
   getchar();
   char str[10];
   scanf("%s",str);//遇空格结束
   gets(str);//包含空格
  
   //输出
   printf("%s",str);
   puts(str);
   getchar();

   return 0;

}

原文地址:https://www.cnblogs.com/wwwfj/p/3366915.html