[英]How to concatenate characters in C from a string with spaces?
我正在尝试连接 C 中的字符,但没有成功。 问题是获取一个字符串,检查该字符串中是否有空格,然后从该主字符串中空格之后的字母创建一个新字符串。
例子:
主要字符串: hello world wide
新字符串: hww
我不知道如何连接。 我在互联网上进行了研究,发现strcpy
和strcat
函数很有用,但即使使用它们我也没有成功。 同样,我尝试执行类似result += string[i + 1]
的操作,但它不起作用。
源代码
#include <stdio.h>
#include <string.h>
int main()
{
char string[] = "str ing placeholder";
int stringLength = strlen(string);
int i;
char result;
for (i = 0; i < stringLength; i++)
{
if (string[i] == ' ')
{
printf("Found space at the index: %d\n", i);
result = string[i + 1];
printf("\nNext char: %c\n", result);
}
}
return 0;
}
希望有人可以指导我。 我不认为我的程序逻辑是错误的,我只需要将字符串的第一个字符和字符串空格后面的每个字符连接成一个新字符串,然后呈现这个新形成的字符串。
如果你想将结果连接成一个字符串,'result' 应该是一个 char 数组:
//...
char result[4];
int currentWord = 0;
for (i = 0; i < stringLength; i++)
{
if (string[i] == ' ')
{
result[currentWord] = string[i + 1];
currentWord++;
}
}
您的代码的另一个问题是它不会读取第一个单词,因为它之前没有空格。 解决此问题的一种方法是将字符串的第一个分配给单词的第一个元素:
char result[4];
if (string[0] != ' ') result[0] = string[0];
int currentWord = 1;
您还可以使用“strtok_r”来简化事情,实现它的一种方法是这样的:
char *saveptr;
result[0] = strtok_r(string, " ", &saveptr)[0];
for (i = 1; i < 3; i++) // 3 is the word count
{
result[i] = strtok_r(NULL, " ", &saveptr)[0];
}
请注意,“结果”数组的大小是任意的,仅适用于 3 个或更少的单词。 您可以创建一个类似的 for 循环来计算字符串中的空格数以找出有多少单词。
如果您需要更改源数组,使其仅包含存储字符串中单词的第一个字符,则程序可以如下所示。
#include <string.h>
#include <stdio.h>
int main( void )
{
char s[] = "str ing placeholder";
const char *delim = " \t";
for ( char *p = s + strspn( s, delim ), *q = p; *q; p += strspn( p, delim ) )
{
*q++ = *p;
p += strcspn( p, delim );
}
puts( s );
return 0;
}
程序 output 是
啜
您不能使用 C 中的+
或+=
运算符连接字符串或字符。 您必须定义一个足够大的char
数组来接收新字符串并一次将适当的字符存储到其中。
您可能希望将每个单词的首字母复制到缓冲区而不是空格后面的每个字符。
这是修改后的版本:
#include <stdio.h>
int main() {
const char text[] = "Hello wild world!";
char initials[sizeof text]; // array for the new string
int i, j;
char last = ' '; // pretend the beginning of the string follows a space
// iterate over the main string, stopping at the null terminator
for (i = j = 0; text[i] != '\0'; i++) {
// if the character is not a space but follows one
if (text[i] != ' ' && last == ' ') {
// append the initial to the new string
initials[j++] = text[i];
}
last = text[i]; // update the last character
}
initials[j] = '\0'; // set the null terminator in the new string.
printf("%s\n", initials); // output will be Hww
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.