Comparing portions of strings?

I am trying to write a version of bubblesort that will take in an array of strings and sort the strings. Each string has 15 characters of letters and numbers to compare as well as a name afterward. I want to be able to sort them based on all 15 characters as well as a range of characters (ie. characters 2-5)

The following is my current code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void bubblesort(string data[], int lowbound, int highbound, int size)
{
	int comparesize=highbound-lowbound+1;
	char firststring[comparesize], secondstring[comparesize];
	for (int i=size-1; i>=1; i--)
	{
		for(int j=0; j<i; j++)
		{
			if (lowbound==0 && highbound==14) //this part works
			{
				if (data[j]>data[j+1]) data[j].swap(data[j+1]);
			}
			else //this part doesnt
			{
				data[j].copy(firststring,comparesize,lowbound);
			      data[j+1].copy(secondstring,comparesize,lowbound);
				if (firststring>secondstring) data[j].swap(data[j+1]);
			}
		}
	}
}


when i sort based on all 15 characters, the string comparison operator (string1>string2) works fine. However, the only way I could think of comparing portions of the strings would be to copy the range of characters from each string and then compare those, but the string::copy member function only writes to arrays of chars, not actual strings. Is there an easier way to do this?

Thanks,

Psychocowtipper
closed account (1yR4jE8b)
Use the std::string class's substr() function:

string substr ( size_t pos = 0, size_t n = npos ) const;

Where pos is the position of the first character in the substring, and n is the number of characters you want in the substring.

So, for example (keep in mind I did not test this), to compare only the first three characters of a string:

1
2
3
4
     std::string s1 = "footastic", s2 = "bartacular";

     if(s1.substr(0, 3) < s2.substr(0, 3))
          ;//doStuff 
Ah, I forgot all about substr! Thanks!
Topic archived. No new replies allowed.