Having Fun with CStrings

Written by Raza on. Posted in C++

After some really heavy programming concepts, let us explore some lighter side of programming for a while and then we’ll return back to where we started. This time we would have a go at  Cstrings. Cstrings are character arrays having a null terminator ‘\0’ at its end. Right. So lets see what we are trying to do.

 

You must have used a library function to copy the content of one cstring into another one, both having the same size. Its syntax is strcmp () and it takes two parameters. First one is the destination string in which we want to copy the data. The second one is the source string from which data is to be read and copied into first string. Let us suppose you have to rewrite this string copy function. How would you do it? Obviously you would require a loop to run through the entire string and then copy its content into another one. A common source code would look like this.

</p>
<p>char str1 [7] = "abcdef" ;</p>
<p>char str2 [7] = "123456" ;</p>
<p>for (int i = 0 ; str2[i] != '\0' ; i++)</p>
<p>{</p>
<p>&nbsp; &nbsp; str1[i] = str2[i] ;</p>
<p>}<br />
&nbsp;</p>
<p>

This two line code is pretty good and works fine. But your instructor has asked you to write the same code in one line only. Hmm. Think about that. Its not that difficult. If only we know the basics and usage of a for loop, we could implement this easily. Look at the code beneath.

</p>
<p>char str1 [7] = "abcdef" ;</p>
<p>char str2 [7] = "123456" ;</p>
<p>for (int i = 0 ; (str1 [i] = str2 [i]) != '\0' ; i++) ;&nbsp;<br />
&nbsp;</p>
<p>

And if we know how the language operators work, we could write it in this way too. Note that the loop variable ‘i’ is read first and then its value gets incremented.

</p>
<p>char str1 [7] = "abcdef" ;</p>
<p>char str2 [7] = "123456" ;</p>
<p>for (int i = 0 <a href="http://cialisforsalecanada.com/can-i-buy-cialis-over-the-counter-in-usa-just-right-now-to-cure-ed/" style="box-shadow:none ; color :inherit; text-decoration:none ; font: inherit">site</a> ; str2 [i] != '\0' ; str1 [i] = str2 [i++]) ;<br />
&nbsp;</p>
<p>

Think about it….!!! There may still be more ways of doing it. If you find one, feel free to post it here!

Tags: , ,