例句:“我有一个笔头,我有一个菠萝,Uh..pineapplepen,菠萝笔。”
问题1:请在例句中打印出钢笔这个词的位置。将C语言应用于Arduino.
问题2:在例句中,所有的“钢笔”改为“苹果”注意:不包括凤梨的钢笔。请解释代码。将C语言应用于Arduino.
我的朋友是C#做的,但我不知道如何将C语言应用于Arduino.
//by C#
using System;
using System.Text.RegularExpressions;
class HelloWorld {
static void Main() {
var source = "I have a pen.I have a pineapple. Uh..pineapplepen. pen pineapple apple pen.";
String target= "pen";
Regex regex= new Regex("(^|[\\s.,])("+ target + ")(?=[\\s.,])");
foreach(Match match in regex.Matches(source)) {
Console.WriteLine(match.Index+match.Groups[1].Length);
}
var result= regex.Replace(source,x=>x.Groups[1]+"apple");
Console.WriteLine(result);
Console.ReadLine();
}
}
发布于 2022-01-03 08:43:38
在例句中,所有的“钢笔”改为“苹果”注意:菠萝的钢笔不包括在内。
出现问题时,"apple"
比"pen"
长,因此更改意味着形成比原始字符串更长的字符串。我们需要一个新的空间来形成结果。
“不包括菠萝粉笔”意味着我们需要定义一个词的概念,也许是
[beginning or whitespace]pen[end or whitespace]
。
考虑一个2通过的解决方案,第一个确定所需的大小,第二个来做替代。
一些未经测试的OP代码,以了解如何实现各种问题。
// Look for a needle in a haystack
// Replace when found, form result in dest (when not NULL)
// Return string length
size_t sub(char *dest, const char *haystack, const char *needle, const char *replace) {
size_t needle_len = strlen(needle);
size_t replace_len = strlen(replace);
if (needle_len == 0) {
TBD_Code(); // Handle pathological case
}
bool beginning_of_word = true;
size_t dest_i = 0;
// Walk the haystack
for (size_t i = 0; haystack[i]; ) {
if (beginning_of_word && memcmp(&haystack[i], needle, needle_len) == 0) {
unsigned char end = haystack[i + needle_len];
if (isspace(end) || end) {
if (dest) {
strcpy(dest + dest_i, replace);
}
dest_i += replace_len;
i += needle_len;
beginning_of_word = false;
continue;
}
}
unsigned char ch = haystack[i];
beginning_of_word = isspace(ch);
if (dest) {
dest[dest_i] = ch;
}
dest_i++;
i++;
}
if (dest) {
dest[dest_i] = 0;
}
return dest_i;
}
用法
const char *example = "I have a pen.I have a pineapple. Uh..pineapplepen. pen pineapple apple pen.";
size_t len = sub(NULL, example, "pen", "apple");
char dest[len + 1];
sub(dest, example, "pen", "apple");
puts(dest);
基本的复杂性是C不像其他语言那样具有组合的字符串/内存分配例程。所以我们需要用用户代码来处理这个管理。
https://stackoverflow.com/questions/70566637
复制