[英]Inputting and reversing multiple strings in C?
第一次在這個論壇發帖,但不是第一次瀏覽它! 非常有用的線程,現在我覺得是時候尋求一些幫助了,所以提前感謝那些可以幫助我的人。
我有以下幾行代碼:輸入時顛倒單詞的順序。
即輸入:你好,我是蝙蝠俠輸出:蝙蝠俠,我在那里你好
現在我想讓用戶能夠輸入多個字符串,即 ''Hello there I am Batman'' ; ''你好,世界'' ; 等等。理想情況下,這些在輸入時由分號分隔並用它進行解析。
代碼:
#include <stdio.h>
/* function prototype for utility function to
reverse a string from begin to end */
/*Function to reverse words*/
void reverseWords(char* s)
{
char* word_begin = NULL;
char* temp = s; /* temp is for word boundry */
/*STEP 1 of the above algorithm */
while (*temp) {
/*This condition is to make sure that the string start with
valid character (not space) only*/
if ((word_begin == NULL) && (*temp != ' ')) {
word_begin = temp;
}
if (word_begin && ((*(temp + 1) == ' ') || (*(temp + 1) == '\0'))) {
reverse(word_begin, temp);
word_begin = NULL;
}
temp++;
} /* End of while */
/*STEP 2 of the above algorithm */
reverse(s, temp - 1);
}
/* UTILITY FUNCTIONS */
/*Function to reverse any sequence starting with pointer
begin and ending with pointer end */
void reverse(char* begin, char* end)
{
char temp;
while (begin < end) {
temp = *begin;
*begin++ = *end;
*end-- = temp;
}
}
/*
int main( void )
{
int i, n;
printf("Enter no of strings:");
scanf("%i", &n);
char **str = (char **) malloc( n* sizeof(char*));
for (i = 0; i < n; i++) {
str[i] = (char*) malloc(100);
fgets(str[i],100,stdin);
}
for (i = 0; i < n; i++) {
printf("%s", str[i]);
}
for (i = 0; i < n; i++) {
free(str[i]);
}
free(str);
return 0;
}
*/
/* Driver function to test above functions */
int main()
{
char str[50];
char* temp = str;
printf("Enter a string : ");
gets(str);
reverseWords(str);
printf("%s", str);
return(0);
}
使用其中一條評論中提到的strtok
,您可以這樣做:
void reverseSentence(char* sent){
char *argv[25]; // This assumes you have a max of 25 words
int argc = 0;
char* token = strtok(sent, " ");
while (token != NULL) {
argv[argc] = malloc(100); // This assumes each word is 99 characters at most
strcpy(argv[argc++], token);
token = strtok(NULL, " ");
}
for(int z = argc-1; z>=0; z--)
fprintf(stdout, "%s ", argv[z]);
fprintf(stdout, "\n");
}
警告! 我沒有測試代碼,所以你可能有一些錯誤......比如缺少分號,變量名不匹配等......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.