[英]Add one character from a string to the end of another string (strcat)
for (unsigned int i = 0; i < strlen(s); i++) {
if (s[i] != ' ')
strcat(p, s[i]);
I want to add the current character of the s
string at the end of the p
string provided it is not a space. 我想在p
字符串的末尾添加s
字符串的当前字符,前提是它不是空格。 How do I do that using strcat
? 我如何使用strcat
做到这一点? The code above gives the following error "invalid conversion from 'char' to 'const char*'". 上面的代码给出以下错误“从'char'到'const char *'的无效转换”。
I want to use strcat
because this way I don't have to store an index for p string in order to know where to place the current character. 我要使用strcat
因为这样就不必知道p字符串的索引就可以知道当前字符的位置。 I hope this makes sense. 我希望这是有道理的。
Also, I need to do this using array of chars, not c-strings or whatever those are called. 另外,我需要使用字符数组来执行此操作,而不是使用c字符串或任何被称为的字符串。
A more sensible algorithm would avoid using strcat()
or strncat()
altogether: 一个更明智的算法将避免完全使用strcat()
或strncat()
:
int j = strlen(p);
for (int i = 0; s[i] != '\0'; i++)
{
if (s[i] != ' ')
p[j++] = s[i];
}
p[j] = '\0';
This avoids quadratic behaviour which using strlen()
and strcat()
(or strncat()
) necessarily involves. 这避免了使用strlen()
和strcat()
(或strncat()
)必然涉及的二次行为。 It does mean you need to keep a track of where to place characters in p
, but the work involved in doing that is trivial. 这确实意味着您需要跟踪将字符放置在p
,但是这样做的工作很简单。 Generally speaking, the quadratic behaviour won't be a problem on strings of 10 characters or so, but if the strings reach 1000 bytes or more, then quadratic behaviour becomes a problem (it takes 1,000,000 operations instead of 1,000 operations — that can become noticeable). 一般而言,在10个字符左右的字符串上,二次行为不会有问题,但是如果字符串达到1000个字节或更多,则二次行为就会成为问题(它需要1,000,000次操作,而不是1,000次操作-这会变得很明显)。
First, you need addresses (the array itself is an address to the first element) to pass to the strcat
, not a char
. 首先,您需要将地址(数组本身是第一个元素的地址)传递给strcat
,而不是char
。 That is why you need to use the &
operator before s[i]. 这就是为什么您需要在s [i]之前使用&
运算符。
You have a working example here 您在这里有一个有效的例子
#include <stdio.h>
#include <string.h>
int main()
{
char s[50]= "Hello World";
char p[50]= "Hello World";
for(unsigned int i=0;i<strlen(s);i++){
if(s[i]!=' ')
strncat(p,&s[i],1);
}
puts(p);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.