c - 无法更改 C 中字符串的最后一个索引的内容?
问题描述
我目前在更改字符串内容方面遇到一些问题。
我正在编写的以下程序重新排列字符串 src 中以辅音开头的单词,使辅音在后面结束(bob --> obb)。以元音开头的单词保持不变。结果被插入到字符串 dest。
然而,句子输入的最后一个词总是以一个缺失的辅音结尾(bob --> ob)。这表明我无法更改字符串 dest 的最后一个索引的内容。
有什么原因吗?
void convert(char src[], char dest[]) {
int i, isVowel, first_pos;
int len = strlen(src);
int count = 0;
char first = 0;
for (i = 0; i < len; i++) {
while (!isspace(src[i])) {
if (first == 0) {
first = src[i];
first_pos = i;
}
isVowel = first == 'a' || first == 'e' || first == 'i' || first == 'o' || first == 'u';
if (isVowel == 1) {
dest[count++] = src[i];
}
else if (i != first_pos) {
dest[count++] = src[i];
}
i++;
}
if (isVowel == 0) {
dest[count++] = first;
}
dest[count++] = ' ';
first = 0;
}
}
输入:“hi guy” 预期输出:“ih uysg” 实际输出:“ih uys”
解决方案
你应该改变
while (!isspace(src[i])) {
至
while (src[i] && !isspace(src[i])) {
最后添加功能
dest[count++] = '\0';
修改后的代码:
void convert(char src[], char dest[]) {
int i, isVowel, first_pos;
int len = strlen(src);
int count = 0;
char first = 0;
for (i = 0; i <= len; i++) {
while (src[i] && !isspace(src[i])) {
if (first == 0) {
first = src[i];
first_pos = i;
}
isVowel = first == 'a' || first == 'e' || first == 'i' || first == 'o' || first == 'u';
if (isVowel == 1) {
dest[count++] = src[i];
}
else if (i != first_pos) {
dest[count++] = src[i];
}
i++;
}
if (isVowel == 0) {
dest[count++] = first;
}
dest[count++] = ' ';
first = 0;
}
dest[count++] = '\0';
}
推荐阅读
- javascript - 如何使用 Sequelize ORM 从日期字段按月和年分组
- python - Salesforce API totalSize 并不总是与返回的行数匹配
- c# - 如何更改 linq 查询以使法国标准在一条记录中
- winforms - SSO 不适用于 IdentityModel.OidcClient
- hive - Hive:解析嵌套的 json 列表
- git - 仅当文件夹中的文件在上次拉取时发生更改时才运行部分脚本
- ruby-on-rails - Rails 6 + ActionMailbox (mail.decoded) 失败并带有表情符号任何其他意外输入
- python - 如何格式化红色的负百分比和绿色的正百分比?
- amazon-web-services - 当没有作业运行时,为什么 AWS Glue 会显示“超出最大并发运行次数”?
- authentication - 使用 ZAP-CLI 创建 ZAP 上下文