arrays - 在排除用户输入字符时难以将 char 数组字符分配给另一个 char 数组
问题描述
总的来说,我对 C 语言和编程还是很陌生。
作为一项家庭作业,我需要制作一个程序,让用户输入一个单词,然后输入一个字母,在该程序中,该程序打印出这些字母在该单词中的位置并打印出没有这些字母的单词(这就是我现在正在苦苦挣扎的地方)。
这是现在的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char word[20];
printf("Enter a word: ");
scanf("%s", word);
int length = strlen(word);
char letter[1];
printf("Enter a letter: ");
scanf("%s", letter);
char newWord[20];
for(int i = 0; i < length; i++){
if(word[i] != letter[0]){
newWord[i] = word[i];
} else
if(word[i] == letter[0]){
printf("%s is at %d\n", letter, i+1);
//newWord[i] = word[i+1]; // I've commented this out because I was testing the first part
// of the loop which is assigning those letters to the variable
// and yet still can't think of an idea that skips that letter
// I want it to skip.
}
}
printf("%s", newWord);
}
基本上我从最后一次打印printf("%s", newWord);
中得到的只是空白。但我想要它做的是例如我输入“worlrdr”和“r”,所以它打印“wold”。甚至一些基本的东西newWord[i] = 'z';
,比如:
for(int i = 0; i < length; i++){
if(word[i] != letter[0]){
newWord[i] = word[i];
}
打印出“zz`zz(一些奇怪的字符)”。我真的很困惑,如果有人能解释一下,我将不胜感激。
提前谢谢你!
解决方案
我已经粉碎(删除)在字符串中找到的所有字母并将字符从长度转移到找到的字母索引
此代码可以帮助您:
#include <stdio.h>
#include <string.h>
int main()
{
char word[20];
printf("Enter a word: ");
scanf(" %s", word);
int length = strlen(word);
char letter;
printf("Enter a letter: ");
scanf(" %c", &letter);
for(int i=0;i<length;i++)
{
if(word[i]== letter )
{
printf("%c is at %d\n", letter, i+1);
}
}
//here is the for loop of crushed
for(int i=0;i<length;i++)
{
if(word[i]== letter )
{
for(int j=i+1;j<length;j++)
{
word[j-1]=word[j];
}
length--;
i--;
}
}
printf("\nDisplay of the string :\n\n");
for(int i=0;i<length;i++)
{
printf("%c", word[i]);
}
printf("\n");
}
例子 :
输入字符串="MLMAZELMLMMLLAMMMMAR"
字母 ='M'
输出字符串:“LAZELLLLAAR”
或者,您可以使用第二个字符串将单词 1 的字母复制到单词 2,除了与给定字母相同的字符
#include <stdio.h>
#include <string.h>
int main()
{
char word[20];
printf("Enter a word: ");
scanf(" %s", word);
int length = strlen(word);
char letter;
printf("Enter a letter: ");
scanf(" %c", &letter);
for(int i=0;i<length;i++)
{
if(word[i]== letter )
{
printf("%c is at %d\n", letter, i+1);
}
}
char word2[20];
int j=0;
for(int i=0;i<length;i++)
{
if(word[i]!= letter )
{
word2[j]=word[i];
j++;
}
}
printf("\nDisplay of the new string(word 2) :\n\n");
for(int i=0;i<j;i++)
{
printf("%c", word2[i]);
}
printf("\n");
}
例子 :
输入字符串(单词 1)="MLMAZELMLMMLLAMMMMAR"
字母 ='M'
输出字符串(单词 2):“LAZELLLLAAR”
推荐阅读
- javascript - wordpress js 移动重定向脚本仅在前页不起作用时
- javascript - 每次我运行 java 脚本代码时,如何创建一个唯一值?
- java - (JAVA) 可能存在 Thread.sleep() 问题的基于文本的游戏
- reactjs - 有没有理由不将反应组件作为属性传递?
- r - 文本挖掘 - 查找以前缀开头的单词
- json - 从 Swift 2.3 中的 JSON html 字符串解析
- javascript - Jquery 选择器上下文不工作
- javascript - 组合和编码挑战
- html - 将css导入html时找不到错误
- request - Angular 5 - 类型安全的 http.get 请求和除 json 之外的其他响应类型?