这是我第一次用C语言编写,我必须编写一个代码来对字符串进行上限,而实际上并没有使用上限。我这样做了,但是由于某种原因它最多只能使用8个字符。...-----这是输入“ hello hello hellohello”(倒数第二个和最后一个hello之间有2个空格)-----这是输出:字符串的长度是24字数是4复制:hello hello hello hello;▒大写的字符串是HELLO HEp▒▒▒原始字符串是hello hello hello hello
#include <stdio.h>
int strLength(char* str){
int count;
for(count=0;str[count] != '\n';count++){}
return count;
}
int numWords(char* str){
int count = 0;
for(int i=0;str[i] != '\n';i++){
if(str[i] == ' ' && str[i+1] != ' ' && str[i+1]!='\n'){
count ++;
}
}
return count+1;
}
char* copyStr(char* str,char* str2){
for(int i=0;str[i] != '\n';i++){
char n = str[i];
str2[i] = n;
}
str2[strLength(str)] = '\n';
return str2;
}
char* upper(char* str){
char str2[100];
for(int i=0;str[i] != '\n';i++){
int current = str[i];
if((current >= 97) && (current <= 122)){
char new = str[i];
str2[i] = new-32;
}
else{
str2[i] = current;
}
}
char* str3 = str2;
return str3;
}
int main(int argc, char **argv){
char input[100];
char inputcopy[100];
//get the input string
printf("Enter string: ");
fgets(input, 100, stdin);
printf("The length of the string is %d\n",strLength(input));
printf("The number of words is %d\n",numWords(input));
copyStr(input,inputcopy);
printf("Copy: %s\n", inputcopy);
printf("The capitalized string is %s\n",upper(inputcopy));
printf("The original string is %s",input);
}
明显的问题:
copyStr
中的副本upper
中的局部变量的指针