arrays - 用用户输入字符串替换提供的字符串?
问题描述
我将以这曾经有效的事实作为开头。我添加了一个打印语句(现在已经消失),它只是要求用户输入字符串。
输入是通过以下方法完成的:
./Project aa b
aa
是要替换的代码,并且b
将是替换用户输入中任何出现的字母的字母。
因此对于
./project Timmy Johhny
Timmy strolled through the park
输出将是
Johhny strolled through the park.
正如我所说,它确实有效,之后只是打印了空格。
我的代码如下所示:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char * isMatch(char* os, char* ns, char* us){
int i;
int oslen, nslen, uslen;
int it = 0;
uslen = strlen(us);
oslen = strlen(os);
nslen = strlen(ns);
for(i=0; i < uslen; i++){
if(strstr(&us[i], os) == &us[i]){
it = it + 1;
i = i + oslen - 1;
}
}
char *ans = malloc(uslen + nslen * it);
int anslen = uslen + nslen * it;
i = 0;
while(*us){
if(strstr(us, os) == us){
strcpy(&ans[i], ns);
i = i + nslen;
us = us + oslen;
}
else
ans[i++] = *us++;
}
return ans;
}
int main(int arg1, char * argp[]){
char input[100];
int i;
char c;
while(1){
if(scanf("%c",&c)==EOF){
break;
}
if( (input[0]=c) != '\n'){
for(i=1;i<100;i++){
scanf("%c", &input[i]);
if(input[i] == '\n'){
break;
}
// char *match = isMatch(argp[1],argp[2],&input[i]);
// printf("%s", match);
// free(match);
}
char *match = isMatch(argp[1],argp[2],&input[i]);
printf("%s", match);
free(match);
}
}
}
我只是犯了一个小错误,还是更大的错误。我试图将 printf 移入和移出 for 循环以及其他所有内容,只是得到了越来越奇怪的输出。
谢谢!
解决方案
推荐阅读
- node.js - 猫鼬数据库中的计算问题
- ios - 如何将 AppTrackingTransparency 权限添加到您的 iOS 应用程序
- arrays - 如何打印出由 C 中的 char ** 创建的字符串(数组)数组?
- spring - 使用 tomcat 部署我的战争文件时出现问题
- java - java.sql.SQLException:参数索引超出范围(4 > 参数个数,即 3)
- python - 我想知道如何在我的代码的一部分被使用并且不再需要之后“隐藏”它
- arrays - 当使用带有一系列选项的 swiftui 选择器时。如何将所选选项而不是索引值保存到 Cloud Firestore?
- algorithm - 为什么福特-富尔克森如此普遍?
- mongodb - 如何在 MongoDB `$jsonShema` 的模式中使用正则表达式?
- java - 如何在 Spring 数据 Elasticsearch 中将对象列表查询为 Map