我正在做一些在C在互联网上的挑战,并得到了以下使命:
给定一个字符串,该字符串由一个接一个的升序字符(按ASCII值)组成,返回相同的字符串,但用一个减号替换序列的中间字母
示例:给定以下输入:dabcefLMNOpQrstuv567 zyx(美国)
我们预期会有下列输出:头孢噻肟钠-OpQr-v567 zyx
我试过的代码:
/* Importing useful libs */
#include <stdio.h>
#include <string.h>
/* Declaring boolean definitions */
typedef enum {
false,
true
}
bool_enum;
/* Declaring Max. Input Length */
#define MAX_INPUT_LENGTH 80
void sequence_replace(char string[]);
/* Main Function */
int main() {
char input_str[MAX_INPUT_LENGTH];
printf("Please enter the string you'd like to switch its sequences with the three char method: ");
scanf("%s", input_str);
sequence_replace(input_str);
return 0;
}
void sequence_replace(char string[]) {
int first_char, last_char;
int slen = strlen(string);
bool_enum sequence = false;
for(int i = 0; i < slen; i ++) {
int s1 = string[i];
int s2 = string[i+1];
if (s1 + 1 == s2) {
if (sequence = false) {
sequence = true;
first_char = i;
}
}
if (s1 + 1 != s2) {
if (sequence = true) {
last_char = i;
string[first_char + 1] = '-';
for(int j = first_char+2; j < last_char; j++) {
string[j] = '';
}
}
sequence = false;
}
}
printf("Sequences after replacement are: %s", string);
}
基本上,我尝试做的是在sequence_replace函数中迭代字符串,直到我找到一个字符,其ascii代码+ 1等于下一个字符的ascii代码,我将布尔标志更改为true,以表明我在序列中,并保留序列的第一个字符出现时的索引,那么一旦它遇到其ASCII码-1不等于先前字符ASCII码的字符,然后,我将第一个字符后面的字符切换为“-”sign,然后运行一个循环,直到序列结束,用空字符串替换所有其他字符。不幸的是,似乎不起作用,如果可能的话,希望得到任何帮助。
1条答案
按热度按时间wsxa1bj11#
For starters there is no need to introduce this typedef declaration
It is much better just to include the header
<stdbool.h>
and use namesbool
,false
andtrue
defined in the header.The function itself should be declared like
Using the function
strlen
is redundant and inefficient.As it follows from the provided example you should check whether a current character is an alpha character or not.
You may not declare integer character constants that do not contain a symbol like this
That is in C there are no empty integer character constants.
Also there is a logical error in this if statement (apart from the typo in the inner of statement
if (sequence = true) {
where there is used the assignment operator=
instead of the equality operator==
)It unconditionally write the symbol
'-'
even if there are only two characters that satisfy the conditionIn this case according to the provided example the symbol
'-'
is not inserted.Also for example the for loop will not process the tail of the string that represents an increased sequence of letters.
The function can look the following way as shown in the demonstration program below.
The program output is