18.09.2011, 01:02
(
Последний раз редактировалось [HiC]TheKiller; 18.09.2011 в 03:07.
)
Understanding Strings
Introduction
I've made this tutorial for the newer people that don't understand the basic concepts of strings. There is quite a few topics with people very confused on why they cant just compare two strings together with the equals to in PAWN. I'm pretty much going to discuss what strings are and why you cant do that.
What are strings?
Strings are multi-celled variables that can store words and letters in them. We use them to format basic strings, compare text such as passwords and usernames. You may be a bit confused on why you cannot just go ahead and do
pawn Код:
new string;
format(string, sizeof(string), "Hello");
//or
new string = "Hello";
pawn Код:
new string[6] = "Hello";
pawn Код:
new string[6] = "Hello";
printf("%d", string[0]);
pawn Код:
new string[6] = "Hello";
printf("%s", string[0]);
Why cant I just compare it using '=='?
This is kinda answered above really. '==' is used to compare single cells, whereas strings are multi celled. You can however compare every single letter to each other. This is comparing the numbers which are actually letters in the single cells so
pawn Код:
new string1[6] = "hello";
new string2[5] = "hell";
if(string1[0] == string2[0])
{
//Do something
}
pawn Код:
new string1[6] = "Hello";
new string2[6] = "Hello";
for (new id; id<6; id++)
{
if(string1[id] != string2[id]) return false; //If the strings don't equal (They do though).
}
return true;
What are single quotes used for in strings ( ' and ' )?
Single quotes are used for pretty much changing a letter into a number. There is a few uses for this such as checking if a single letter at a certain place in a string.
pawn Код:
public OnPlayerText(playerid, text[])
{
if(text[0] /*Text[0] is a single cell of the string text */ == '@')
{
//Do something
}
return 1;
}
Checking if a string is empty
There is a few methods that allow us to check if strings are empty or not. Our first one is
pawn Код:
if(!string[0])
We could also use EOS to check if there is nothing in there. EOS is pretty much just representing "\0" which also represents 0.
pawn Код:
if(string[0] == EOS)
//Is actually if(string[0] == '\0')
Conclusion
This was a pretty rushed tutorial. I tried to cover the subject but not in too much depth so that the readers would get lost half way through it. I hope that you kind of understand how strings work now
![Smiley](images/smilies/smile.png)