简体   繁体   English

使用strcat将字符附加到C中的字符串

[英]Appending character to a string in C with strcat

Hi guys I'm still really confused with pointers and I'm wondering if there's anyways to do the following without having to use sprintf: 嗨伙计们,我仍然真的很困惑指针,我想知道是否有任何事情要做以下,而不必使用sprintf:

char a[100], b[100], c[2];

//Some code that puts a string into a 

for(i = 0; i<strlen(a); i++)
{
    if(a[i] == 'C')
        strcat(b, "b");
    else if(a[i] == 'O')
        strcat(b, "a");
    else if(a[i] == 'D')
        strcat(b, "1");
    else
    {
        sprintf(c, "%s", a[i]);
        strcat(b, c);
    }
}

pretty much a for loop looping through a string(an array) and filling up another string with a character(or string) depending on what the character is, if the character ain'T C, O or D it just adds it to the other string. 几乎是一个for循环遍历一个字符串(一个数组)并用字符(或字符串)填充另一个字符串,具体取决于字符是什么,如果字符不是C,O或D,它只是将它添加到另一个串。

  • I can't seem to just do strcat(b, a[i]); 我似乎不能只做strcat(b, a[i]); and I understand that it wouldn't work because it would try strcat(char *, char) instead of char*, const char*) . 我明白它不会工作,因为它会尝试strcat(char *, char)而不是char*, const char*)
    Is there anyway I can turn it into a pointer? 无论如何我可以把它变成指针吗? they still confuse me so much..and I'm new to programming in general just to low level languages... 他们仍然让我很困惑......而且我对初级编程只是为了低级语言......

  • also what would be the best way to initialize char[] s? 还有什么是初始化char[]的最佳方法? that are gonna be filled with a string, what I use right now is : 这将填充一个字符串,我现在使用的是:

     char ie[30] = "" 
  • Also let me know if there's any easier way to do what 如果有更简单的方法可以让我知道

I want and sorry if it's unclear this is obviously a throwaway script but the same concept is used in my script. 我想要并且抱歉,如果不清楚这显然是一个一次性的脚本,但在我的脚本中使用了相同的概念。

Thank you in advance stackoverflow :X 谢谢你提前stackoverflow:X

(1) One bug may be in your code: (1)您的代码中可能包含一个错误:

You are commenting that Some code that puts a string into a , and I think you don't assign any string to b . 您正在评论一些将字符串放入a的代码,我认为您不会将任何字符串分配给b so by default char b[100]; 所以默认情况下char b[100]; have garbage value (may not present \\0 in b ). 有垃圾值( b可能不存在\\0 )。 but string concatenation function expects that b must be a string. 但字符串连接函数期望b必须是一个字符串。 So 所以

strcat(b, "b");   <--will Undefined Behavior 

(2) A technique to initialize empty string: (2)初始化空字符串的技巧:

Yes you should always initialize you variable (array) with default values like: 是的,您应该始终使用默认值初始化变量(数组),例如:

char a[100] = {0}, b[100] = {0}, c[2] = {0};

note: remaining elements of a half initialize array would be 0 (null), Initialize a variable assume to be good practice 注意:半初始化数组的剩余元素将为0 (null),初始化变量假定为良好实践

(3) Yes strcat(b, a[i]); (3)strcat(b, a[i]); is wrong: 是错的:

To concatenate string from a[i] on words into b you can do like: 要将单词a[i]上的字符串连接到b你可以这样做:

strcat(b, a + i);

yes you are correct strcat(b, a[i]); 是的,你是正确的strcat(b, a[i]); is not valid indeed. 确实无效。

note: a[i] and (a + i) are not same, a[i] is char type, where as (a + i) is string that is type of a . 注意: a[i](a + i)不相同, a[i]是char类型,其中as (a + i)a类型的字符串。

Suppose you have following string array a and value of i is 2 then: 假设您有以下字符串数组a并且i值为2则:

+----+----+----+---+---+----+----+----+---+
| 'u'| 's' |'e'|'r'|'5'| '6'| '7'|'8' | 0 |  
+----+----+----+---+---+----+----+----+---+
 201   202  203 204 205 206  207   208 209 210  211
  ^          ^  
  |          |
  a         (a+i) 

So in above diagram a values is 201 and type is char [100] (assuming array is 100 in size) (a + i) also points a string from 'e' at address 203 . 因此,在上图中a值为201 ,类型为char [100] (假设数组大小为100) (a + i)也指向地址 203处的'e'字符串。 where as a[i] = 'e' 其中a[i] = 'e'

So you can't do strcat(b, a[i]); 所以你不能做strcat(b, a[i]); but strcat(b, a + i); 但是strcat(b, a + i); is valid syntax. 是有效的语法。

Additionally, From @BenVoigt to concat n chars from a from i th position you can do like: 此外,从@BenVoigt到Concat的n从字符ai日,你可以做这样的位置:

strncat(b, a+i, n);

its will append n char from a+i to b . 它将从a+ib附加n字符。

既然你要采取的一个子a一个字符长:

strncat(b, a+i, 1);

Initialize all char array to null so that no garbage values exists in code. 将所有char数组初始化为null,以便代码中不存在垃圾值。

You are appending to garbaged char array. 你附加了garbaged char数组。

char a[100]={0}, b[100]={0}, c[2]={0};

Now strcat() function behaves properly. 现在strcat()函数表现正常。

There are many possible ways to do as you wish. 有许多可能的方法可以按照您的意愿去做。 There are ways that avoid using strcat() and sprintf() altogether — see below; 有一些方法可以避免完全使用strcat()sprintf() - 见下文; you can avoid sprintf() while continuing to use strcat() . 你可以在继续使用strcat()时避免使用sprintf() strcat()

The way I'd probably do it would keep a record of where the next character is to be added to the target string, b . 我可能会这样做的方法是记录下一个字符添加到目标字符串的位置, b This will be more efficient since repeatedly using strcat() involves quadratic behaviour as you build up a string one character at a time. 这将更有效,因为重复使用strcat()涉及二次行为,因为您一次构建一个字符串。 Also, it is generally best to avoid using strlen() in the loop condition for the same reason; 此外,出于同样的原因,通常最好避免在循环条件下使用strlen() ; it is (probably) evaluated on each iteration, so that it too leads to quadratic behaviour. 它(可能)在每次迭代时进行评估,因此它也会导致二次行为。

char a[100], b[100];
char *bp = b;

//Some code that puts a string into a 
size_t len = strlen(a);

for (int i = 0; i < len; i++, bp++)
{
    if (a[i] == 'C')
        *bp = 'b';
    else if(a[i] == 'O')
        *bp = 'a';
    else if(a[i] == 'D')
        *bp = '1';
    else
        *bp = a[i];
}
*bp = '\0';   // Null-terminate the string

You could also do without the pointer by using the index variable i to assign to b (as long as you only add one character to the output for each input character): 你也可以在没有指针的情况下使用索引变量i来分配给b (只要你只为每个输入字符的输出添加一个字符):

char a[100], b[100];

//Some code that puts a string into a 
size_t len = strlen(a);

for (int i = 0; i < len; i++)
{
    if (a[i] == 'C')
        b[i] = 'b';
    else if(a[i] == 'O')
        b[i] = 'a';
    else if(a[i] == 'D')
        b[i] = '1';
    else
        b[i] = a[i];
}
b[i] = '\0';   // Null-terminate the string

As long as the string in a is short enough to fit, the code shown (either version) cannot overflow b . 只要在该字符串a足够短,以适应,所示的代码(或者版本)不能溢出b If you sometimes added several characters to b , you'd either need to indexes ( i and j ), or you could increment the pointer bp in the first version more than once per loop, and you'd need to ensure that you don't overflow the bounds of b . 如果你有时为b添加了几个字符,你需要索引( ij ),或者你可以在每个循环中多次增加第一个版本中的指针bp ,并且你需要确保你不要t溢出b的界限。

You seem to be confused in regards to strings . 你似乎对字符串感到困惑。 A string isn't just an array. 字符串不仅仅是一个数组。 Which book are you reading? 你正在读哪本书?

When you first call strcat to operate on b , b isn't guaranteed to be a string. 当你第一次调用strcat来操作bb不能保证是一个字符串。 The result is undefined behaviour. 结果是未定义的行为。 This code might seem to function correctly on your system, but if it does then that is by coincidence. 此代码似乎在您的系统上正常运行,但如果确实如此,那就巧合了。 I have seen code like this fail in strange ways on other systems. 我看到这样的代码在其他系统上以奇怪的方式失败了。 Fix it like this: 修复如下:

char a[100], b[100];

//Some code that puts a string into a
a[x] = '\0'; // <--- Null terminator is required for a to contain a "string".
             //      Otherwise, you can't pass a to strlen.

for(i = 0; i<strlen(a); i++)
{
    if(a[i] == 'C')
        b[i] = 'b';
    else if(a[i] == 'O')
        b[i] = 'a';
    else if(a[i] == 'D')
        b[i] = '1';
    else
        b[i] = a[i];
}

b[i] = '\0'; // If you don't put a null character at the end, it isn't a string.

Now, what is a string? 现在,什么是字符串?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM