[英]The end character `\0` is it considered as one character or two characters?
[英]Changing character in a string to two characters
您好,我在使用strchr()時遇到問題,因為是的,它將返回指向該字符首次出現的指針,但是如何從中獲取索引以進行更改呢? 如何將一個字符更改為兩個字符? 因此,我需要將src中的每個“ x”更改為目標中的“ ks”。
我的代碼:
#include <stdio.h>
#include <string.h>
void antikorso(char *dest, const char *src) {
strcpy(dest, src);
if (strchr(dest, 'x')) {
}
printf("\n%s", dest);
}
int main(void) {
const char *lol = "yxi yxi";
char asd[1000];
antikorso(asd, lol);
}
以下代碼行可能會有所幫助:
#include <stdio.h>
#include <string.h>
void antikorso(char *dest, const char *src) {
int j=0;
for(int i=0;i<strlen(src);i++)
{
if (src[i] == 'x')) {
dst[j]='k';
j++;
dst[j] = 's';
j++;
}
else
{
dst[j] = stc[i];
j++;
}
i++;
}
dst[j] = '\0';
printf("\n%s", dest);
return dest;
}
int main(void) {
const char *lol = "yxi yxi";
char asd[1000];
antikorso(asd, lol);
}
您可能不需要索引,僅需要一個指針。 “索引”將是從開頭的偏移量,因此dest[i]
與dest + i
相同,后者是dest
的地址,再加上i
字符。 因此,您可以使用:
char *cp;
if (cp=strchr(dest, 'x')) {
*cp= 'y';
但是,如果您確實想要索引,它只是
if (cp=strchr(dest, 'x')) {
int i = cp - dest;
你可以做:
void antikorso(char *dest, const char *src) {
const char *p = src;
int i;
for (i = 0; *p != '\0'; i++, p++) {
if (*p != 'x') {
dest[i] = *p;
} else {
dest[i++] = 'k';
dest[i] = 's';
}
}
dest[i] = '\0';
printf("\n%s", dest);
}
其他答案不是不正確的,只是想解決一個重要問題:通過寫越過目標緩沖區的末尾,您將無法避免未定義的行為(與如今像strcpy
或strcat
這樣的許多stdlib函數一樣,這是不安全的)! 因此,我強烈建議您修改函數簽名(如果您可以這樣做):
size_t antikorso(char* dest, size_t length, const char* src)
// ^^ ^^
{
char* d = dest;
char* end = d + length;
for(; *src; ++src, ++d)
{
// not much different than the other answers, just the range checks...
if(d == end)
break;
*d = *src;
if(*d == 'x')
{
*d = 'k'
if(++d == end)
break;
*d = 's';
}
}
// now null-terminate your string;
// first need to get correct position, though,
// in case the end of buffer has been reached:
d -= d == end;
// this might possibly truncate a trailing "ks";
// if not desired, you need extra checks...
*d = 0;
return d - dest;
}
返回值不會增加任何安全性,但是可以防止您一旦寫入就必須在輸出上調用strlen
。
如果strchr
返回有效地址,則可以通過減去“基地址”(即,指向數組第一個元素的指針),使用指針算法來獲取索引。
#include <string.h>
#include <stddef.h> // NULL, ptrdiff_t
const char* result = strchr(dest, 'x');
if ( result != NULL)
{
ptrdiff_t index = result - dest;
... // do stuff with index
}
ptrdiff_t
是適合於表達指針算術結果的標准C整數類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.