3.2—字符串—Implement strStr()

描述
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

#include<iostream>
#include<string>
#include<vector>
using namespace std;
int ImplementStr(string mainstr, string substr)
{
	int mainlegth = mainstr.size();
	int sublength =substr.size();
	for (int i = 0; i < mainlegth;i++)
	{
		int k = i;
		int j;
		for (j = 0; j < sublength;j++)
		{
			if (mainstr[k] == substr[j]&&k<mainlegth)
			{
				k++;
			}
			else
				break;
		}
		if (j == sublength)
			return i;
	}
	return -1;
}
int main()
{
	string mainstr = "I LOVE SEU UNIVERSITY IN NANJING china!";
	string substr = "china!";
	int index = ImplementStr(mainstr, substr);
	cout << index << endl;
}

要将从机接收到的字符串显示在LCD1602上,可以分为以下几个步骤: 1. 初始化串口和LCD1602,设置串口波特率和LCD1602的显示模式、数据线连接方式等。 2. 在从机中启用串口接收中断或者轮询方式读取串口接收缓冲区中的数据,并将接收到的数据存储到一个缓冲区中,直到接收到一个完整的字符串。可以根据特定的结束符(如换行符 `\n` 或者 null 结尾符 `\0`)来判断字符串是否接收完整。 3. 在主循环中,不断检查缓冲区中是否有新的完整字符串,如果有则将其显示在LCD1602上。可以使用 LCD1602 的库函数来实现字符串的显示。 下面是一个示例代码,演示了如何将从机接收到的字符串显示在LCD1602上: ```c #include <stdio.h> #include <string.h> #include <lcd1602.h> #define BUF_SIZE 128 char buf[BUF_SIZE]; int buf_pos = 0; void uart_rx_handler(char c) { if (buf_pos < BUF_SIZE - 1) { buf[buf_pos++] = c; if (c == '\n') { // received a complete string buf[buf_pos] = '\0'; // add null terminator lcd_gotoxy(0, 0); // move cursor to first line lcd_puts(buf); // display the string on LCD1602 buf_pos = 0; // reset buffer position } } else { // buffer overflow buf_pos = 0; // reset buffer position } } int main() { // initialize UART module and enable receive interrupt // TODO: implement UART initialization // initialize LCD1602 module lcd_init(LCD1602_4BIT_MODE, LCD1602_2LINE_MODE, LCD1602_5x8DOTS_MODE); while (1) { // TODO: read data from UART receive buffer // and call uart_rx_handler() for each received byte } return 0; } ``` 在上面的示例代码中,我们使用了 LCD1602 的库函数 `lcd_gotoxy()` 和 `lcd_puts()` 来将接收到的字符串显示在LCD1602上。其中,`lcd_gotoxy(0,0)` 将光标移动到LCD1602的第一行第一列,`lcd_puts(buf)` 将缓冲区中的字符串显示在LCD1602上。需要注意的是,为了防止缓冲区溢出,需要限制缓冲区的大小,并在缓冲区满时清空缓冲区。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值