Преобразуйте строку в C++ к верхнему регистру

method1 существует в ABC.prototype, и вы можете шпионить за ним и заменить реализацию до создания нового экземпляра ABC:

class ABC {
  constructor() {
    this.method1();
  }
  method1() {
    throw new Error('should not get here');
  }
}

test('ABC', () => {
  const spy = jest.spyOn(ABC.prototype, 'method1');  // spy on the method of the prototype
  spy.mockImplementation(() => {});  // replace the implementation
  const abc = new ABC();  // no error
  expect(spy).toHaveBeenCalled();  // SUCCESS
})
258
задан tshepang 17 July 2012 в 01:31
поделиться

9 ответов

Boost string algorithms:

#include <boost/algorithm/string.hpp>
#include <string>

std::string str = "Hello World";

boost::to_upper(str);

std::string newstr = boost::to_upper_copy<std::string>("Hello World");
205
ответ дан 23 November 2019 в 02:39
поделиться

not sure there is a built in function. Try this:

Include either the ctype.h OR cctype libraries, as well as the stdlib.h as part of the preprocessor directives.

string StringToUpper(string strToConvert)
{//change each element of the string to upper case
   for(unsigned int i=0;i<strToConvert.length();i++)
   {
      strToConvert[i] = toupper(strToConvert[i]);
   }
   return strToConvert;//return the converted string
}

string StringToLower(string strToConvert)
{//change each element of the string to lower case
   for(unsigned int i=0;i<strToConvert.length();i++)
   {
      strToConvert[i] = tolower(strToConvert[i]);
   }
   return strToConvert;//return the converted string
}
0
ответ дан 23 November 2019 в 02:39
поделиться

try the toupper() function (#include ). it accepts characters as arguments, strings are made up of characters, so you'll have to iterate over each individual character that when put together comprise the string

2
ответ дан 23 November 2019 в 02:39
поделиться
typedef std::string::value_type char_t;

char_t up_char( char_t ch )
{
    return std::use_facet< std::ctype< char_t > >( std::locale() ).toupper( ch );
}

std::string toupper( const std::string &src )
{
    std::string result;
    std::transform( src.begin(), src.end(), std::back_inserter( result ), up_char );
    return result;
}

const std::string src  = "test test TEST";

std::cout << toupper( src );
7
ответ дан 23 November 2019 в 02:39
поделиться

Есть ли в строках символы ASCII или International?

Если это последний случай, «верхний регистр» не так прост, и это зависит от используемого алфавита. Существуют двухпалатные и однопалатные алфавиты. Только двухпалатные алфавиты имеют разные символы для верхнего и нижнего регистра. Также есть составные символы, такие как латинская заглавная буква «DZ» (\ u01F1 «DZ»), которые используют так называемый регистр заглавия . Это означает, что изменяется только первый символ (D).

Я предлагаю вам взглянуть на ICU и разницу между простым и полным отображением регистра. Это может помочь:

http://userguide.icu-project.org/transforms/casemappings

20
ответ дан 23 November 2019 в 02:39
поделиться
struct convert {
   void operator()(char& c) { c = toupper((unsigned char)c); }
};

// ... 
string uc_str;
for_each(uc_str.begin(), uc_str.end(), convert());

Note: A couple of problems with the top solution:

21.5 Null-terminated sequence utilities

The contents of these headers shall be the same as the Standard C Library headers , , , , and [...]

  • Which means that the cctype members may well be macros not suitable for direct consumption in standard algorithms.

  • Another problem with the same example is that it does not cast the argument or verify that this is non-negative; this is especially dangerous for systems where plain char is signed. (The reason being: if this is implemented as a macro it will probably use a lookup table and your argument indexes into that table. A negative index will give you UB.)

28
ответ дан 23 November 2019 в 02:39
поделиться
#include <algorithm>
#include <string>

std::string str = "Hello World";
std::transform(str.begin(), str.end(),str.begin(), ::toupper);
471
ответ дан 23 November 2019 в 02:39
поделиться

Использование Повышения. Текст, который будет работать на текст Unicode

boost::text::text t = "Hello World";
boost::text::text uppered;
boost::text::to_title(t, std::inserter(uppered, uppered.end()));
std::string newstr = uppered.extract();
1
ответ дан 23 November 2019 в 02:39
поделиться
//works for ASCII -- no clear advantage over what is already posted...

std::string toupper(const std::string & s)
{
    std::string ret(s.size(), char());
    for(unsigned int i = 0; i < s.size(); ++i)
        ret[i] = (s[i] <= 'z' && s[i] >= 'a') ? s[i]-('a'-'A') : s[i];
    return ret;
}
10
ответ дан 23 November 2019 в 02:39
поделиться
Другие вопросы по тегам:

Похожие вопросы: