如何获得字符串帮助中最小的字母! [英] How do I get the smallest letter in the string help!

查看:87
本文介绍了如何获得字符串帮助中最小的字母!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试试这个,

这是错的?



消息:分段错误(核心转储)



我的尝试:



i try this,,
this is wrong?

the message : Segmentation fault (core dumped)

What I have tried:

int n;
	string s;
        cout << "Long string : ";
	cin >> n;
        cout << "String = ";
   	cin >> s;
	string y = s;
	for(int i = 0; i < n; i++)
	{
		for(int j = i+1; j < n; i++)
		{
			if(y[i] > s[j])
			{
				s[i] = s[j];
				s[j] = y[i];
			}
		}
return 0;
	}

推荐答案

你知道, C ++ 编程语言功能标准库:

You know, the C++ programming language features a Standard Library:
#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
  string s;
  cout << "please enter a string: \n";
  cin >> s;
  auto it = min_element( s.cbegin(), s.cend());
  
  if ( it != s.cend())
    cout << "the smallest letter in the string is '" << *it << "'" << endl;
}


为什么你认为你需要两个嵌套循环?特别是当你在它们中增加 i 而不是 i 中的一个,并且 j 在另一个?



而不是嵌套循环,想想你将如何手动完成:

你会以空的最低值开始(因此将其设置为最大值 - 然后所有其他值都小于它)并且您将查看字符串中的每个字符一次,将其与当前最低进行比较。

如果它相同或更大,你会忽略它。

否则,你将最低设置为当前值。



循环后,最低是最小的字母。



那么为什么要运行嵌套循环?
Why do you think you need two nested loops? Particularly when you increment i in both of them instead of i in one, and j in the other?

Instead of a nested loop, think how you would do it manually:
You would start with an empty "lowest" value (so set it to the biggest possible - then all the others are smaller than it) and you would look at each character in the string once, comparing it against the current "lowest".
If it's the same or bigger, you'd ignore it.
Otherwise, you'd set the "lowest" to the current value.

After the loop, the "lowest" is the smallest letter.

So why run nested loops?


除了已经提到的在内循环中递增 i 而不是 j 之外还有另一个错误:

您正在访问字符串的字符,直到索引 n 。如果 n 大于字符串的长度,那将无效。



这两个错误都会导致绑定访问(访问字符串使用的内存中的字符)导致未定义的行为或 - 在最坏的情况下 - 这里 - 分段错误。



而不是让用户输入 n 的值,使用输入字符串的长度:

There is another error besides the already mentioned one of incrementing i instead of j in the inner loop:
You are accessing the characters of the strings up to the index n. That won't work if n is greater then the length of the strings.

Both errors result in out of bound accesses (accessing characters out of the memory used by the strings) which result in undefined behaviour or - in the worst case as here - segmentation faults.

Instead of letting the user enter the value for n, use the length of the entered string:
int n = s.length();

使用它来搜索解决方案1中建议的最小字母。

Use that to search for the smallest letter as suggested in solution 1.


这篇关于如何获得字符串帮助中最小的字母!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆