我试图编写一个函数,使用指针将字母转换为两个星号(*
)。
例如:
输入:
hello12345good++//--ok
输出:
**********123456********++//--****
我写了一个将字母改成两个相同字母的字母,但却无法为*
写字。
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int points_converter(char str[])
{
char *s, *s1;
int f = 0;
for (s = str; *s; s++)
{
if(isalpha(*s))
{
f = 1;
s1 = s;
s = s + strlen(s);
while(s != s1 - 1)
*(s+1) = *(s--);
s = s + 2;
}
}
return f;
}
int main()
{
char str[81];
int f;
puts("Input string:");
while (strlen(gets(str)) >= 81);
f = points_converter(str);
if (f == 0)
{
puts("No latin letters in string.");
}
else
{
puts("New string: ");
puts(str);
}
return 0;
}
答案 0 :(得分:3)
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdbool.h>
bool points_converter(char str[]){
bool f = false;
char *temp = malloc(strlen(str)*2+1);
char *s = str, *d = temp;
if(!temp){
perror("malloc:");
return f;//no change
}
for (; *s; s++){
if(isalpha((unsigned char)*s)){
f = true;
*d++ = '*';
*d++ = '*';
} else {
*d++ = *s;
}
}
*d = 0;
strcpy(str, temp);//`str` must have enough spaces.
free(temp);
return f;
}
#define MAX_LENGTH 40
int main(void){
char str[MAX_LENGTH * 2 + 1];
while(true){
puts("Input string:");
fgets(str, MAX_LENGTH+1+1, stdin);//+1:newline, +1:NUL. Use fgets instead of gets
char *p = strchr(str, '\n');
if(p){
*p = '\0';//chomp newline
break;
} else {
while (getchar() != '\n');//Input too long, clear input
}
}
if (points_converter(str)) {
puts("New string: ");
puts(str);
} else {
puts("No latin letters in string.");
}
return 0;
}
答案 1 :(得分:-1)
怎么样:
static const int MAXINPUTLEN=81;
int points_converter(const char* input, char *output)
{
int count = 0; // initialize counter to zero
while (*input) { // while input is not pointing to zero
if (isalpha(*input)) { // if input is pointing to alpha
output[0] = '*'; // replace first byte pointed to by output with '*'
output[1] = '*'; // replace 2nd byte pointed to by output with '*'
output += 2; // increment output by 2
count++; // increment counter
} else {
*output = *input; // copy non-alpha to output
output++; // increment output by one
}
input++; // increment input pointer by one
}
*output = 0; // terminate output with zero byte
return count; // return count
}
int main()
{
char input[MAXINPUTLEN + 1];
char output[2 * MAXINPUTLEN + 1];
gets(input); // not checking for input overflow!
points_converter(input, output);
}