我必須從用戶獲取輸入,並找到那些10串最長的輸入..從C中的十個字符串列表中找出最長的字符串?
#include<stdio.h>
#include<conio.h>
void main() {
char str[10][10]
printf("Enter strings:")
scanf("%s", str)
}
我若用戶輸入這個樣子,將其存儲在字符串str中二維數組?要找出最長的字符串,我會找到每個字符串的長度,並使用max_length函數來確定最長的字符串。
我必須從用戶獲取輸入,並找到那些10串最長的輸入..從C中的十個字符串列表中找出最長的字符串?
#include<stdio.h>
#include<conio.h>
void main() {
char str[10][10]
printf("Enter strings:")
scanf("%s", str)
}
我若用戶輸入這個樣子,將其存儲在字符串str中二維數組?要找出最長的字符串,我會找到每個字符串的長度,並使用max_length函數來確定最長的字符串。
您不需要存儲所有字符串,只是迄今爲止輸入的最長字符串。 請注意,您需要定義最大字符串長度以避免緩衝區溢出。
例如:
#define MAX_STRING_SIZE 1024
char last_entered_string[MAX_STRING_SIZE];
char longest_entered_string[MAX_STRING_SIZE] = ""; /* Must be initialized. */
scanf("%1023s", last_entered_string); /* Read one less to allow for
null terminator. */
使用循環來接受十個輸入和最長的字符串進行比較。如果最後輸入的字符串較長,則將其複製到最長的字符串中。由於這是功課,我不會提供任何進一步的代碼。
不,它不會。你必須循環閱讀所有的字符串。
for(i=0;i<10;i++)
scanf("%s", str[i]);
此外,你錯過了一些分號!
您可以找到最長的字符串put並將其保存爲接收到的所有字符串。
int main()
{
char *str = NULL;
char *compare;
printf("Enter strings:");
scanf("%s", compare);
if (strlen(str) < strlen(compare))
str = strdup(compare);
return(0);
}
如果你想存儲所有用戶輸入的(考慮到你可以從用戶只有10串),你可以這樣做:
int main()
{
char **array;
char *str;
int x = 0;
int shortest;
array = malloc(sizeof(char*) * 10);
while (x < 10)
{
scanf("%s", str)
array[x] = strdup(str);
x++;
}
x = 0;
shortest = x;
while (x < 10)
{
if (strlen(array[x]) > strlen(shortest))
shortest = x;
x++;
}
return (0);
}
最短將是最長的字符串的索引在你的數組中。
我希望這會幫助你。
我想盡可能地做到最簡單的方法。請問上面的代碼有效嗎?它是完整的程序嗎? –
我沒有測試過,因爲我沒有gcc或者其他的東西,但是我認爲它可以工作(你將不得不做一個返回數組[x]字符串的函數,這是最長的字符串) 。只要測試一下,無論如何都很容易調試 –
將所有輸入存儲在一個數組中,然後做qsort()
它對數組條目的長度,然後取第一個(或最後一個,取決於你如何排序)條目。
好吧,好吧...... - 這可能是過度設計... ;-)
我覺得你可以做的只是嵌套循環和排在搜索'\0'
性格和運行什麼計數器同時。只要你找到一個'\0'
停止計數器並將計數器的值存儲在一個單獨的數組中。所以現在你將有一個10個整數的數組。 現在搜索數組中的最小整數...賓果! 相應的行將具有最短的字符串。 我知道這種方法非常原始,但我認爲這對於僅具有C基本知識的人會有幫助。
該程序將從用戶處取得10個輸入字符串,然後最終打印出最長的字符串及其長度。它不會存儲比最大的輸入字符串。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STR_LEN 1024
int main(int argc, char **argv){
char str_final[MAX_STR_LEN];
char str_temp[MAX_STR_LEN];
unsigned int i, j, len_str;
unsigned int num_string = 10;
unsigned int len_max = 0;
for (i=0; i<num_string; i++){
printf("Enter string number: %d\n", i);
gets(str_temp);
for (j=0; str_temp[j]; j++);
len_str = j;
if(len_str > len_max){
len_max = len_str;
memset(str_final, 0, MAX_STR_LEN);
memcpy(str_final, str_temp, len_str);
}else{
memset(str_temp, 0, MAX_STR_LEN);
}
}
printf("The biggest string is: %s\n", str_final);
printf("It's size is: %d\n", len_max);
exit(EXIT_SUCCESS);
}
有沒有更簡單的方法來做到這一點?我搞砸了! –
@ user1687755,我想不出一個更簡單的方法。一次完成一步:1)編寫一個接受一個輸入並打印的程序。 2)擴展程序接受10個輸入('for(int i = 0; i <10; i ++)'並打印每個輸入。3)修改它符合您的最終要求。 – hmjd