Sign in to follow this  

Problem with char arrays

This topic is 4592 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Ok, say I have: char String[32]; Say String[0] = 'H'; String[1] = 'e'; String[2] = 'l'; String[3] = 'l'; String[4] = 'o'; So the first 5 characters of the char array are "Hello" Now what I want to do is something like this: if (String == "Hello") //do something But String never equals "Hello", it equals "Hello", and then 26 bytes of junk, or nothing. So how can I see if String has "Hello" in it? or any other string in it? Any help is appreciated, -Dev578

Share this post


Link to post
Share on other sites
Firstly, you should add

String[5] = '\0';

which is called the null terminator and defines where the end of the string is. To compare strings, you'll want to use strcmp, to search one string for another, use strstr.

tj963

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Add '\0' into the last real data array entry (i.e. in your case [5]), and then check for "Hello".

Otherwise cast it to a CString and then check it.

Share this post


Link to post
Share on other sites
using strcmp

syntax of strcmp:
int strcmp(const char *str1, const char *str2);


The strcmp() function lexicographically compare two strings and returns an integer based on the outcome.

Less than 0 mean str1 is less than str2
0 mean str1 is equal to str2
Greater than 0 mean str1 us greater than str2

example :

#include <string>
#include <iostream>

int main()
{
char strTest[] = "Hello";
if (strcmp(strTest, "Hello") == 0) std::cout << "It is equal";
}

Share this post


Link to post
Share on other sites
Quote:
Original post by MaulingMonkey
Quote:
Original post by Enigma
If you're using C++ then use std::string.

Enigma


Quoted for being the best answer.

std::string string;
string = "Hello";

if ( string == "Hello" )


Add a vote from over here, too (as if there were any doubt). :)

Share this post


Link to post
Share on other sites

This topic is 4592 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this