1.状态模式
switch语句
计算字符串里面的英文字母个数
#include<stdio.h>
#include<ctype.h>
#include<assert.h>
#include<limits.h>
#include<string.h>
#include<stdlib.h>
#include<time.h>
#include<windows.h>
#define BEGIN 1
#define IN_WORD 2
#define OUT_WORD 3
#define END 4
int GetWordNum(const char* str)//状态模式编程方案
{
assert(str != nullptr);
int num = 0;
int tag = BEGIN;
for (const char* p = str; *p != '\0'; ++p)//p指针直到扫描完整个字符串才终止结束
{
switch (tag)
{
case BEGIN:
if (isalpha(*p))
{
tag = IN_WORD;
}
else
{
tag = OUT_WORD;
}
break;
case IN_WORD:
if (!(isalpha(*p) || *p == '\'' || *p == '-'))
{
tag = OUT_WORD;
num += 1;
}
break;
case OUT_WORD:
if (isalpha(*p))
{
tag = IN_WORD;
}
break;
}
}
if (tag = IN_WORD)
{
num += 1;
}
return num;
}
int main()
{
char str1[] = { "yhping tulun's new-data hello data" };
char str2[] = { "yhping tulun newdata hello data" };
int num = GetWordNum(str1);
printf("%d \n", num);
num = GetWordNum(str2);
printf("%d \n", num);
return 0;
}
2.输出数组元素最大值和第二大的数值
#include<stdio.h>
#include<ctype.h>
#include<assert.h>
#include<limits.h>
#include<string.h>
#include<stdlib.h>
#include<time.h>
#include<windows.h>
void Print2Max(int ar[], int n)
{
assert(ar != nullptr && n > 1);
int max1 = ar[0] > ar[1] ? ar[0] : ar[1];
int max2 = ar[0] < ar[1] ? ar[0] : ar[1];
for (int i = 2; i < n; ++i)
{
if (ar[i] > max1)
{
max2 = max1;
max1 = ar[i];
}
else if (ar[i] > max2)
{
max2 = ar[i];
}
}
printf("max:%d max2:%d \n", max1, max2);
}
int main()
{
int ar[] = { 12,45,67,23,100,78,34,56,89,90 };
int n = sizeof(ar) / sizeof(ar[0]);
Print2Max(ar, n);
return 0;
}
方法一:
#include<stdio.h>
#include<assert.h>
#include<string.h>
#include<stdlib.h>
#include<limits.h>
#include<ctype.h>
int maxProfit(int* prices, int n)
{
assert(prices != nullptr && n > 0);
int max = 0;
for(int i = 0; i < n; ++i)
{
for (int j = i + 1; j < n; ++j)
{
if (prices[j] - prices[i] > max)
{
max = prices[j] - prices[i];
}
}
}
return max;
}
int main()
{
int prices[] = { 7,1,5,3,6,4 };
int n = sizeof(prices) / sizeof(prices[0]);
int maxv = maxProfit(prices, n);
printf("maxv:%d \n", maxv);
return 0;
}