初学指针,刷题(hznu【C系列5.6】指针专题之翻译)

发布时间 2023-12-11 14:31:17作者: Blizzard1900

题目如下

Description

 (本人学艺不精,写了很久才写出了一个臃肿的代码,malloc也不咋会用,只能向ai请教了T_T)

Alex在朋友们都去生猴子了的日子里,日复一日、年复一年地敲代码,终于,在经年累月的摧残下,她的手指变得不那么利索了,比如“how are you”她会哆嗦着打成“hhoow areee youuu”,如果两个及以上的字母同时出现,则被认为是多打出来的,她想请你帮忙做的事情就是正确翻译出她想要表达的语句。

 

Input

 

输入多组数据。

每组一行包含空格的字符串,长度不超过10000。

 

Output

 

Alex想要表达的语句。

 

Samples

 

input 
I wwantt apple.
output 
I want aple.

 

 
 
下附ai写的ac代码
 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 
 5 // 函数声明,用于去除字符串中相邻且重复的字符
 6 void translateSentence(char *sentence);
 7 
 8 int main() {
 9 char sentence[10000];
10 
11 // 多组数据输入
12 while (1) {
13 // 从标准输入获取一行字符串
14 if (fgets(sentence, sizeof(sentence), stdin) == NULL || sentence[0] == '\n') {
15 break; // 如果输入为空行或者遇到 EOF(Ctrl+D),结束循环
16 }
17 
18 // 调用函数去除相邻重复字符并打印结果
19 translateSentence(sentence);
20 }
21 
22 return 0;
23 }
24 
25 // 函数定义,去除字符串中相邻且重复的字符
26 void translateSentence(char *sentence) {
27 // 初始化一个指针,用于动态存储处理后的字符串
28 char *result = NULL;
29 size_t resultSize = 0; // 存储已分配内存的大小
30 
31 // 使用strtok函数分割字符串,获取每个单词
32 char *word = strtok(sentence, " ");
33 while (word != NULL) {
34 // 初始化一个字符数组,用于存储处理后的单词
35 char cleanedWord[strlen(word) + 1];
36 int cleanedIndex = 0; // 记录处理后的单词长度
37 char prevChar = '\0'; // 记录前一个字符
38 
39 // 遍历单词中的每个字符
40 for (int i = 0; i < strlen(word); i++) {
41 // 如果当前字符和前一个字符不相同,则加入cleanedWord
42 if (word[i] != prevChar) {
43 cleanedWord[cleanedIndex++] = word[i];
44 prevChar = word[i];
45 }
46 }
47 
48 cleanedWord[cleanedIndex] = '\0'; // 结尾添加空字符
49 
50 // 计算新的内存大小并重新分配内存
51 resultSize += strlen(cleanedWord) + 1;
52 result = (char *)realloc(result, resultSize);
53 if (result == NULL) {
54 fprintf(stderr, "内存分配失败\n");
55 exit(EXIT_FAILURE);
56 }
57 
58 // 将处理后的单词加入result中,并加入空格
59 strcat(result, cleanedWord);
60 strcat(result, " ");
61 
62 word = strtok(NULL, " "); // 获取下一个单词
63 }
64 
65 if (resultSize > 0) {
66 result[resultSize - 1] = '\0'; // 移除最后一个空格
67 }
68 
69 // 打印处理后的结果
70 printf("%s\n", result);
71 
72 // 释放动态分配的内存
73 free(result);
74 }