gpt4 book ai didi

c - 如何更改字符串中的每个字符但不更改 C 中的标点符号?

转载 作者:太空宇宙 更新时间:2023-11-04 04:10:40 24 4
gpt4 key购买 nike

我有一项任务是创建一个程序,该程序通过在命令行中输入的一组数字来转换字符串中的每个字符。示例:如果用户在命令行输入 1,然后输入 abc, def,则程序应将字符串转换为 bcd, efg

我写了程序,但我不知道如何让程序不转换标点符号。

程序当前转换abc, def 并打印bcdefg。它需要打印 bcd, efg 并包含标点符号而不转换它们。

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

int main(int argc, string argv[]) //user enter number at cmd prompt

{
string key = argv[1]; //store user entered number
int k = atoi(argv[1]); //only accept consecutive digits
if (argc != 2 || k == 0)
{
printf("Usage: ./caesar key\n"); /*show error if user enters non-consecutive digits*/
return 1;
}
string original = get_string("Plaintext: "); /* prompt user for message to spin*/

for (int i = 0, n = strlen(original); i < n; i++) /* get string length and loop char change*/
if (isalnum(original[i])) /* only convert alphanumeric character*/
printf("%c", original[i] + k); /* print and convert character by number entered at prompt*/

printf("\n");
return 0;
}

最佳答案

您只输出您正在转换的字符(那些在 isalnum 集合中的字符)。您还需要输出未转换的字符。例如:

    char cipher = original[i] ;
if( isalnum( original[i] )
{
cipher += k ;
}

printf( "%c", cipher ) ;

然而,所描述的算法在几个方面仍然存在严重缺陷,但不清楚是作业有缺陷(在这种情况下这不是您的问题)还是您对作业的描述不准确。

一个更实用的解决方案可能是这样的:

#include <ctype.h>

char caesar( char x, int key )
{
const char alphabet[] = {'a','b','c','d','e','f','g','h',
'i','j','k','l','m','n','o','p',
'q','r','s','t','u','v','w','x',
'y','z',
'0','1','2','3','4','5','6','7','8','9'};

char cipher = x ;

for( int i = 0;
cipher == x && i < sizeof( alphabet );
i++ )
{
if( alphabet[i] == tolower( x ) )
{
cipher = alphabet[(i + key) % sizeof( alphabet )] ;
if( isupper( x ) )
{
cipher = toupper( cipher ) ;
}
}
}

return cipher ;
}

那么你的输出循环将是:

for( int i = 0; original[i] != '\0' ); i++)
{
printf("%c", ceasar( original[i], k ) ) ;
}

关于c - 如何更改字符串中的每个字符但不更改 C 中的标点符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58034160/

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