C:如果字符串内部存在子串,则将字符串中的小写字母改为大写字母

标签 c arrays string pointers substring

我正在编写一个程序,用 C 语言将字符串中的子字符串大写。

以下示例说明了我的预期输出:

String:    "hello world"
Substring: "wo"
Output:    "hello WOrld"
String:    "I don't know how to do this"
Substring: "do" 
Output:    "I DOn't know how to DO this"
String:    "mouse is useful thing"
Substring: "use" 
Output:    "moUSE is USEful thing"
String:    "replace occurrences of 'r'"
Substring: "r" 
Output:    "Replace occuRRences of 'R'"

基本上,子字符串存在于字符串中的任何位置,在原始字符串中都将其大写。

这是我的代码:

void replaceSubstring(char *str, char *substr) {
    char *p = str;
    char *k = substr;
    int substringLength = strlen(k);

    while (*p)
    {
        if (strncmp(p, k, substringLength) == 0)
        {
            for (p; p < p + substringLength; p++)
            {
                *p = *p - 32;
            }
        }
        p++;
    }
    puts(p);
    printf("\n"); 
}

但是,我的代码崩溃了。我的方法是在字符不是 '\0' 时循环,并检查子字符串是否位于字符串中的某个位置(使用 strncmp 函数),以及是否位于,我想通过将 ASCII 值减少 32 来将值 *p 更改为大写字母。

为什么不起作用?哪里错了?

最佳答案

内部循环的主要问题是 p不能同时用作终止目标 ( p + substringLength ) 作为柜台。就像说for (int i = 0; i < i + 10; i++) 。会i曾经到达i + 10

您可以尝试设置 p + substringLength到变量len ,然后使用该固定球门柱作为循环终止条件。

其次,使用toupper()来进行字符转换。否则,空格和非字母字符也将被修改,从而导致意外行为。例如,空格将被转换为空终止字符,从而孤立字符串的尾部。

把它们放在一起产生:

for (char *len = p + substringLength; p < len; p++)
{
    *p = toupper(*p);
}

最后,puts(p);不按你的预期工作。到函数结束时,p用于遍历字符串,现在指向字符串的末尾,而不是开头。使用puts(str);或者简单地从调用范围打印以避免 side effects .

这是一个完整的示例:

#include <ctype.h>
#include <stdio.h>
#include <string.h>

void replaceSubstring(char *str, char *substr) {
    char *p = str;
    int substringLength = strlen(substr);

    while (*p)
    {
        if (strncmp(p, substr, substringLength) == 0)
        {
            for (char *len = p + substringLength; p < len; p++)
            {
                *p = toupper(*p);
            }
        }

        p++;
    }
}

int main(void) {
    char s[12] = "hello world";
    replaceSubstring(s, "llo wor");  
    printf("%s\n", s);
    replaceSubstring(s, "ll");  
    printf("%s\n", s);
    replaceSubstring(s, "h");  
    printf("%s\n", s);
    replaceSubstring(s, "hello worldz");  
    printf("%s\n", s);

    char t[28] = "i don't know how to do this";
    replaceSubstring(t, "do");  
    printf("%s\n", t);
    replaceSubstring(t, "'t know");  
    printf("%s\n", t);
    return 0;
}

输出:

heLLO WORld
heLLO WORld
HeLLO WORld
HeLLO WORld
i DOn't know how to DO this
i DOn'T KNOW how to DO this

Try it!

关于C:如果字符串内部存在子串,则将字符串中的小写字母改为大写字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54187324/

相关文章:

c - 如何修复 :UDP packet send through vlan(eth0. 4092),到达 eth0 和 eth0.4092

python - 从图像中堆叠星 PSF;对齐子像素中心

arrays - 查找 n * m 数组的所有可能组合,不包括某些值

Java StringUtils.stripEnd 带有句点、连字符或下划线

string - typescript :强制类型为 "string literal"而不是 <string>

c - 终止指向指针的指针?

c - 指向指针的通用指针

C Sharedmemory only 1024 int in forked process

c - 获取链接列表fgets和scanf C的输入

c# - 如何删除字符串开头或结尾的所有空格?