Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Editing a string

Posted on 2001-08-14
13
198 Views
Last Modified: 2010-04-02
Lets say someone inputs the string "2001", how would I be able to use a conditional statement on the first two numbers, and then another conditional statement to test the second two numbers.

ie.

if (__first two numbers__ ==20){

first_two_numbers+=1;
cout<<"This is the "<<those_two_numbers<<"st century!";
}

if (__second two numbers__ ==01){
return a;
}

I know I have to split the string into two variables somehow but I'm not sure of the proper way to do it.

Thanks,
Jim
0
Comment
Question by:JSpat
  • 4
  • 3
  • 2
  • +4
13 Comments
 
LVL 3

Expert Comment

by:cwrea
ID: 6385638
First, I assume you are using std::string class, not C-style char[] or char*.

If the string object X contains your string, the following test will be true if and only if the string begins with "20":

if( 0 == X.find("20") )
{
  // executed only if X is of the form ("20...")
  ...
}

For the second test, where you want to see if the next two characters match something, change the 0 to 2 in the if statement.  (When used as above, std::string::find returns the position of the first occurrence of the string passed in.)  So:

if( 2 == X.find("01") )
{
  // executed only if X is of the form ("xx01...")
  ...
}
0
 

Author Comment

by:JSpat
ID: 6385661
I actually was using the c-style char object, how do I use the std::string class?

I upped the points by 25 for the explanation.
0
 
LVL 3

Expert Comment

by:cwrea
ID: 6385744
You can read your input directly into a std::string using std::cin, or you can create a std::string from the C-style char array as follows:

char* x = "chicken";
std::string strX(x);

then use find on strX etc.

I suggest you try and use the C++ standard library instead of the lower level C-style method.  There's a great paper written by Bjarne Stroustrup as to why it is better to learn C++ with higher level abstractions:

http://www.research.att.com/~bs/new_learning.pdf

An excellent book that teaches C++ in such a manner is called "Accelerated C++" by Andrew Koenig and Barbara E. Moo.

Hope that helps.

0
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 6

Accepted Solution

by:
Triskelion earned 100 total points
ID: 6385861
>> I suggest you try and use the C++ standard library instead of the lower level C-style method.


or you can try this...

char strYear[5]="2001";

if (strYear[0]=='2' && strYear[1]=='0') // "20"
   {
   //Do Something here for "20"
   }

if (strYear[2]=='0' && strYear[3]=='1') // "01"
   {
   //Do something here for "01"
   }
0
 
LVL 6

Expert Comment

by:Triskelion
ID: 6385888
...continued...
or you can...


     char strYear[5] = "2001";
     if (!memcmp(strYear, "20", 2))
          {
          //("got 20");
          }

     if (!memcmp(strYear+2, "01", 2))
          {
          //("got 01");
          }
0
 
LVL 1

Expert Comment

by:zmanz
ID: 6385964
>> An excellent book that teaches C++ in such a manner is called "Accelerated C++"

It is a good book. I'm using it right now to learn C++.

http://www.cppreference.com/cppstring.html
0
 
LVL 3

Expert Comment

by:JackThornton
ID: 6386013
hmmmm....

I'm wondering what's wrong with:

int year = atoi(yearAsString);
int century = year / 100;
int yearInCentury = year % 100;

- jack

0
 
LVL 8

Expert Comment

by:mnashadka
ID: 6386495
How about using the C++ string:
char year_str[] = "2001";
std::string century(year_str, 2);
std::string year(&year_str[2], 2);

if(century == "20")
{
 . . .
}
if(year == "01")
{
 . . .
}
0
 
LVL 3

Expert Comment

by:JackThornton
ID: 6386571
To expand on my comment, cout will automatically convert integers to strings; e.g.

cout << "This is the " << 21 << "st Century";

will yield equivalent results to:

cout << "This is the " << "21" << "st Century";

Integers will be much more efficient in subsequent tests; in fact, adding one to the century
(e.g. "first_two_numbers+=1") will *not* work if first_two_numbers is any kind of string variable you can think of (at best a string class will use the += operator to concatenate, turning "20" into "201" instead of "21"). Also, this code does not fail with centuries > 100 (not that a "Year 10001 Problem" is something we have to worry about; it's just somewhat poor form to assume two digits) or centuries < 10 (in case someone is doing a history lesson).

BTW, "atoi" is an old, standard 'C' library function, which is still valid and available in C++, and converts the string to an integer, if possible (it will fail if the first character isn't numeric, '-' or '+'). It will convert as much as possible; so you don't have to necessarily parse the number off the front of a string. For example,
atoi("123 Maplewood Lane") would yield the integer 123.

- jack
0
 
LVL 3

Expert Comment

by:JackThornton
ID: 6386573
To expand on my comment, cout will automatically convert integers to strings; e.g.

cout << "This is the " << 21 << "st Century";

will yield equivalent results to:

cout << "This is the " << "21" << "st Century";

Integers will be much more efficient in subsequent tests; in fact, adding one to the century
(e.g. "first_two_numbers+=1") will *not* work if first_two_numbers is any kind of string variable you can think of (at best a string class will use the += operator to concatenate, turning "20" into "201" instead of "21"). Also, this code does not fail with centuries > 100 (not that a "Year 10001 Problem" is something we have to worry about; it's just somewhat poor form to assume two digits) or centuries < 10 (in case someone is doing a history lesson).

BTW, "atoi" is an old, standard 'C' library function, which is still valid and available in C++, and converts the string to an integer, if possible (it will fail if the first character isn't numeric, '-' or '+'). It will convert as much as possible; so you don't have to necessarily parse the number off the front of a string. For example,
atoi("123 Maplewood Lane") would yield the integer 123.

- jack
0
 
LVL 3

Expert Comment

by:JackThornton
ID: 6386575
<sigh> sometimes I really *hate* what EE does what EE does

double your pleasure, double your fun.... ;-)

- jack
0
 

Expert Comment

by:ssingar
ID: 6395867
Here is a complete program...

#include <iostream>
#include <string>

int main()
{
   char number[20]; //any size you want up to 20

   cin >> number;
 
   std::string numString(number); //construct the string

   if (numString.size() >= 4)
   {
     std::string first2Letters = numString.substr(0,2);
     std::string next2Letters = numStrings.substr(2,2);
 
   //and so on. you can make it more intelligent

   if (first2Letters == "xx") { }//do whatever you want
   if (next2Letters == "yy")  { }//do whatever you want
   }

return 0;
}
0
 
LVL 6

Expert Comment

by:Triskelion
ID: 6396823
I think we lost JSpat.
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Find Visual Studio Tools 2 112
Header of docx file 17 115
How can i compile this github project?? 2 91
Autosar OS Multicore Share Resources confusion ? 2 72
In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

828 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question