在开始之前,这是我的第一个问题,英语不是我的母语,我是 C 编程的新手。我搜索了我的问题但找不到。我的问题是如何打印字符串中的下一个整数。
例如:输入:a2b3d4e5fgh 输出:aabbbdddeeeeefgh
谢谢。
编辑:真正的任务是有一个最多 30 个字符的字符串,当只有带有字符的字符串时,它只是打印输入,但是当有一个以 ' 分隔的字符部分时,它必须包含字符和整数以及字符必须打印下一个整数的数量。
示例输入 1:
abcdefg
示例输出 1:
abcdefg
示例输入 2:
'a2b3c2d2'efg
示例输出 2:
aabbbccddefg
我在这里
int main () {
char number[30];
scanf("%s", &number);
char *part1 = strtok(number, "'");
char *part2 = strtok(NULL, "'");
char *part3 = strtok(NULL, "'");
/*if (number[30]!=0){
printf("Falsche Eingabe");
} */
return 0 ;
}
最佳答案
当然,这个问题需要集中注意力。我不擅长 C,但我可以提出可用于实现此目的的某种逻辑。我还将提供一个 Java 代码示例,我确信它可以轻松地转换为 C。
- 通过用户输入或使用默认值初始化字符串:
字符串数据 = "m3bdfg21tehy4h";字符串 newData="";
- 声明一个变量来存储最后一个非数字字符位置,我们假设第一个字符必须是字母:
int lastNonDigitPosition=0;
- 声明一个 bool 变量,让您知道最后验证的字符是数字还是非数字:
bool 值 isLastCharDigit=false;
- 声明一个变量来存储数字序列(如果一次可以存储超过 1 位数字):
字符串数字序列="";
将 String/CharSequence 转换为字符数组
char[] chars=data.toString().toCharArray();
验证给定位置的每个字符
for (int i=0;i<chars.length;i++)
{
//verify is the current character is not digit
if (!Character.isDigit(chars[i]))
{
if (isLastCharDigit)
{
/*If the last char was a digit, cast the value of digitSequence to integer so you can know how many times you will repeat the character that comes before digit sequence*/
int digitTimes=Integer.valueOf(digitSequence);
//reinitialize the digit sequence
digitSequence="";
for (int j=0;j<digitTimes;j++)
{
//concatenate the last non-digit character to newData digitTimes times
newData+=chars[lastNonDigitPosition];
}
}else{
//if the last char was not a digit just a the character to the String
newData+=chars[i];
}
//save the last non-digit position
lastNonDigitPosition=i;
//inform this current character is not digit
isLastCharDigit=false;
}else{
//if the character is a digit, concatenate with //digitSequence and inform the last char is digit
digitSequence+=chars[i];
isLastCharDigit=true;
}
}
这就是我解决问题的方法。这是JAVA示例,如果有人能翻译成C就好了,我试图解释一下逻辑,让代码更容易理解。
关于c - 将一个字符乘以下一个整数的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53574613/