[英]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.