gpt4 book ai didi

c - C 字符串中的子字符串替换

转载 作者:行者123 更新时间:2023-11-30 20:57:26 25 4
gpt4 key购买 nike

大家好!我决定在这个网站上注册一个帐户来寻求帮助,因为我找不到任何可以帮助我的东西。我有一个需要多个步骤的问题:1)从键盘读取一个字符串;2) 读取一个整数,代表要修改的子字符串的个数(修改就是将字符串中的所有字符都转换为“*”);3)读取所有需要修改的子串;4) 打印修改后的初始字符串。我尝试通过首先设法用一个子字符串来完成它,但是当我读取多个子字符串时我不知道该怎么做。所以,这是版本版本1

#include<stdlib.h>
#include<string.h>
int main()
{
int n;
char str[5120];
char substr[100];
printf("Type the string:\n");
gets(str);
printf("\nType the substring which you would like to modify:");
gets(substr);
char *p;
p = strstr(str,substr);
if (*p != '\0')
{
for( int j=0 ; j< strlen(substr); j++)
{
*p = '*';
p++;
}
}
printf("\nThe modified string is:\n");
for ( int i=0 ; i< strlen(a) ; i++)
{
printf("%c",a[i]);
}
return 0;
}

以及我尝试修改多个的版本

#include<stdlib.h>
#include<string.h>
int main()
{
int n;
char str[5129];
char substr[n][100];
printf("Type the string:\n");
gets(str);
printf("How many substrings to modify?");
scanf("%d",&n);
printf("\nType the substrings:");
for( int i=0 ; i< n ; i++)
{
scanf("%s",substr[i]);
printf(" ");
}
for ( int i=0; i < n; i++)
{
char *p;
p = strstr(str,substr[i]);
if (*p != '\0')
{
for( int j=0 ; j< strlen(cuv[i]); j++)
{
*p = '*';
p++;
}
}
}
printf("\nThe modified string is:\n");
for ( int i=0 ; i< strlen(str) ; i++)
{
printf("%c",str[i]);
}
return 0;
}```
I guess for the n times that I cycle to the string I have to allocate memory somewhere, or I don't know..
Please, I need some help! Thank you!

最佳答案

所以我根据你和@PaulOgilvie的建议编辑了我的答案。我希望该程序现在能够按您的预期运行。

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

#define MAX_SIZE 5129

void replaceSubstring(char *p, int len){
for(int i = 0; i < len; i++, p++){
*p = '*';
}
}

int main() {
int n = 0;
char str[MAX_SIZE];
char substr[n][100];

printf("Type the string:\n");
fgets(str, MAX_SIZE, stdin);

printf("How many substrings to modify?");
scanf("%d",&n);


for( int i=0 ; i< n ; i++) {
printf("\nType the substring number %d:", i+1);
scanf("%s",substr[i]);
}

char *p;
for ( int i=0; i < n; i++){
p = strstr(str, substr[i]);
while(p != NULL) {
replaceSubstring(p, strlen(substr[i]));
p = strstr(str, substr[i]);
}
}

printf("\nThe modified string is:\n");
for ( int i=0 ; i< strlen(str) ; i++)
{
printf("%c",str[i]);
}
return 0;
}

关于c - C 字符串中的子字符串替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59531546/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com