Reputation: 13
So the Problem was given a String Which is a Name like Sam Harris you have to output it's abbreviation what i did was find the space in the string and then taking a string otp which will add str[0] first letter of name str[pos+1] letter after position and also added a . in between but the return statement is returning some random value.Which is not expected. #include
std::string abbrev(std::string str)
{
int pos{0};
for(int i=0;i<str.length();++i)
{
if(str[i]==' ')
{
pos=i;
break;
}
}
std::string otp=str[0]+"."+str[pos+1];
return otp;
}
int main()
{
std::string str="Sam Harris";
std::cout<<abbrev(str)<<"\n";
return 0;
}
Upvotes: 0
Views: 66
Reputation: 808
So you want the first letter, presumably capitalized, for each separate word in the string? Something like this should work.
std::string input = "Sam Harris";
std::string output = "";
auto n = input.find(" ");
while (n++ != input.npos)
{
output += std::to_upper(input[0]);
input = input.substr(n, input.size() - n);
n = input.find(" ");
}
Upvotes: 0
Reputation: 89
str[0] and str[pos+1] returns a character at that position with type char. You cannot added a char variable to a constant string "." (double quoted). Overall I think it added up the constant string memory address with char values of each position and assign it to otp. For example, looking at your case, assume constant string "." have an address value 1000. The str[0] will return 'S' with ascii value 83 and str[pos+1] is expected to return 'H' with ascii value 72. Then opt will assigned with a memory address 1155 (83+1000+72), which will be an unknown program memory with junk value, which will be returned by the function. Use stringstream to concatnate string as following:
std::string abbrev(std::string str)
{
int pos{0};
for(int i=0;i<str.length();++i)
{
if(str[i]==' ')
{
pos=i;
break;
}
}
std::stringstream otp;
otp << str[0] << "." << str[pos+1];
return otp.str();
}
Upvotes: 0
Reputation: 59
Not a c++ guy, but I can give this a shot. I suspect, you're getting random stuff because you're overflowing the bounds of arrays for some inputs. Fixing that may fix your bug (example below, assuming your syntax is correct).
std::string abbrev(std::string str) {
for(int i=0;i<str.length()-1;++i) {
if(str[i]==' ') {
return str[0] + '.' + str[i +1];
}
return '';
}
Obviously you'll have to generalize for arbitrary number of spaces.
Upvotes: -1
Reputation: 16876
The problem is that this here:
str[0]+"."+str[pos+1];
Isn't constructing a string. It's adding a char*
to some chars, effectively performing some invalid pointer arithmetic. Fix it like this:
std::string otp = str[0] + std::string(".") + str[pos + 1];
Now std::string(".")
correctly makes a std::string
and appends those chars as intended using std::string
's operator+.
Upvotes: 2