我需要编写一个名为doubleString
的函数,它接收一个字符串,然后将文本中的所有数字乘以2.该函数应该返回一个指向接收到的字符串的开头的指针,以便于链接.
示例:如果输入字符串为
这个句子包含数字4、数字8和数字88
调用该函数后,字符串应为:
这个句子包含数字8、数字16和数字176
不允许使用string.h
、stdlib.h
库中的函数以及stdio.h
库中的sprintf
和sscanf
函数.不允许在函数中或全局创建助手字符串.
我已经编写了代码,但它只有在输入没有单词的字符串时才起作用,只有数字才起作用.在try 时,我也遇到了一些问题,比如程序对445以上的数字不起作用,或者每次得到不同的输出.这是我当前的代码:
#include <stdio.h>
void inputString(char array[], int size) {
char character = getchar();
if (character == '\n') character = getchar();
int i = 0;
while (i < size - 1 && character != '\n') {
array[i] = character;
i++;
character = getchar();
}
array[i] = '\0';
}
char *doubleString(char *text) {
int carry = 0;
int length = 0;
while (text[length] != '\0') {
length++;
}
for (int i = length - 1; i >= 0; i--) {
if (text[i] >= '0' && text[i] <= '9') {
int digit = ((int)text[i]) * 2 + carry;
carry = digit / 10;
text[i] = (digit % 10) + '0';
}
}
while (carry > 0) {
for (int i = length; i > 0; i--) {
text[i] = text[i - 1];
}
text[0] = (carry % 10) + '0';
carry /= 10;
length++;
}
return text;
}
int main() {
char text[1000];
int size = sizeof(text);
printf("Enter text: ");
inputString(text, size);
char *result = doubleString(text);
printf("'%s'", result);
return 0;
}
该程序在这种情况下不起作用:
输入:
'U ovoj recenici se nalazi broj 4, broj 8 i broj 88'
预期输出:
'U ovoj recenici se nalazi broj 8, broj 16 i broj 176'
我的输出:
'U ovoj recenici se nalazi broj 9, broj 7 i broj 76'
但在这件事上很管用:
输入:
"1 i 1 jesu 2"
预期输出:
'2 i 2 jesu 4'
我的输出:
'2 i 2 jesu 4'