Problem with char arrays

Started by
6 comments, last by Zahlman 18 years, 11 months ago
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
Advertisement
Check strcmp function.
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
tj963
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.
If you're using C++ then use std::string.

Enigma
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" )
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";}
DinGY
Yesterday is history.Tomorrow is a mystery. Today is a gift"
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). :)

This topic is closed to new replies.

Advertisement