如何仅使用一个循环连接/链接字符串数组中的单词? [英] How to connect/link words in an string array using one loop only?
本文介绍了如何仅使用一个循环连接/链接字符串数组中的单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含n个单词的数组..例如,如果数组具有以下字符串,我想将字符串附加在一起:."hello""world""!!"我希望函数返回:"helloworld !!",任何帮助我如何可以在没有递归的情况下并且仅使用一个LOOP来完成类似的事情!而且我只能从字符串库中使用两个函数strcpy和strlen!有任何想法吗 !谢谢
我尝试过的事情:
i have an array with n words .. i want to attach the strings togther .. for example if the array have the following strings: "hello" "world" "!!" i want the function to return :"helloworld!! " any help how i can do something like this without Recursion and with ONE LOOP only !! and i can only use from the string library the two functions strcpy and strlen !! any ideas ! thanks
What I have tried:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * connect( char **words, int n )
{
int length = 0;
for ( int i = 0; i < n; i++ ) length += strlen( words[i] );
char *s = malloc( length + 1 );
int pos = 0;
for ( int i = 0; i < n; i++ )
{
strcpy( s + pos, words[i] );
pos += strlen( words[i] );
}
return s;
}
int main( void )
{
char * s[] = { "Hello", " ", "World" };
int x=(sizeof( s ) / sizeof( *s ));
char *p = connect( s, x);
// puts( p );
free( p );
}
推荐答案
char * connect( char **words, int n )
{
int i = 0 ;
for ( ; i < n ; i++ )
{
*(words [ i ] - 1) = ' ' ;
}
return words [ 0 ];
}
:badger:
:badger:
char *connect(char **words, int n)
{
int i, reqlen = 0, writlen = 0;
char *s = NULL;
for(i = 0; i < n; i++)
{
reqlen += strlen(words[i]) + (i == 0 ? 1 : 0); // addl byte for terminating NULL needed only once
s = realloc(s, reqlen); // add your own code to handle memory allocation failure
writlen += sprintf(s + writlen, "%s", words[i]); // sprintf() returns count of characters written (excluding NULL)
}
return s;
}
这篇关于如何仅使用一个循环连接/链接字符串数组中的单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文