string

I want to get two strings from user and compare them.
I want to see if the letters from the first string are in same order in second one.
for example we have s1,s2 which are our strings.
s1="abcd"
s2="abhcod"
because s1 order is the same in s2 I want to say yes
another example
s1="abcd"
s2="ablldc"
because the order of letters is not the same I want the answer no.

my problem is that I don't know how to compare such strings. oh and the lenght of strings can be anything from 1 to 100.
I tried comparing them but I know I'm doing something wrong.
here is my failed attempt
PS.it doesn't matter how many other characters are between the ltters of s1 in s2. only the order is important

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
  	int i;
 std::string s1;
  std::getline (std::cin,s1);
  std::string s2;
  std::getline (std::cin,s2);
  std::string str ("x");
// getting the strings str is another string which I wanted to make
//so I can try to find letters of s1 in s2 and put them in it
//since I wasn't sure I can leave it empty I put a "x" in it

    i= f.size();

   std::string::size_type found = s2.find_first_of(s1);
 
  while (i>=0 )
  {
    str=str+s2[found];
    found=str.find_first_of(s1,found+1);
    i--;
  }
//the part on top is where my code has a problem if you can help me
//to find a another way or fix this one I'll be really thankfull

s1="x"+s1;
//I added the "x" to fist of s1 so it will be like str

if (str.compare(s1) == 0)
  std::cout << "YES";
 if (str.compare(s1) != 0)
  std::cout << "NO";
  
Hello parinaz mellatdoust,

I hope this helps.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <string>

int main()
{
	std::string s1;
	std::string s2;
	
	int flag = 0;
	
	std::cout << "Enter the 1st string:";
	std::getline(std::cin, s1);
	std::cout << "Enter the 2nd string:";
	std::getline(std::cin, s2);

	for (int cow = 0; cow < s1.size(); cow++)
	{
		if (s1[cow] == s2[cow])
			flag = 1;
		else
		{
			flag = 0;
			cow = s1.size();
		}
	}

	if (flag == 1)
		std::cout << "Yes";

	if (flag == 0)
		std::cout << "No";

	std::cin.ignore();
	return(EXIT_SUCCESS);
}

Last edited on
Registered users can post here. Sign in or register to post.