我正在尝试用用户输入的字符串中的空白字符替换多个字符。该计划的最终目标是计算单词并将标点符号计为空格。比如嘿......算作两个字的人。但是,只有我的最后一次更换工作,我知道为什么,但我不知道如何在不创建多个变量的情况下解决问题,而且我也不想使用数组。所以这是我的代码。
import java.util.Scanner;
class CountWords
{
public static void main(String args[])
{
Scanner scn=new Scanner(System.in);
int wordCounter=0;
String sentence;
String tempPhrase = "";
System.out.print("Enter string >>> ");
sentence = scn.nextLine();
tempPhrase = sentence.replace('.' , ' ');
tempPhrase = sentence.replace(',' , ' ');
tempPhrase = sentence.replace('!' , ' ');
tempPhrase = sentence.replace('?' , ' ');
tempPhrase = sentence.replace(':' , ' ');
tempPhrase = sentence.replace(';' , ' ');
for(int x=0; x < tempPhrase.length()-1; ++x)
{
char tempChar = tempPhrase.charAt(x);
char tempChar1 = tempPhrase.charAt(x+1);
if(Character.isWhitespace(tempChar) &&
Character.isLetter(tempChar1))
++wordCounter;
}
++wordCounter;
if (wordCounter > 1)
{
System.out.println("There are " + wordCounter + " words in the
string.");
}
else
{
System.out.println("There is " + wordCounter + " word in the
string.");
}
}
}
答案 0 :(得分:3)
sentence
,字符串是不可变的,replace
每次都返回一个新的字符串。
你需要这样做:
tempPhrase = sentence.replace('.' , ' ')
.replace(',' , ' ')
.replace('!' , ' ')
.replace('?' , ' ')
.replace(':' , ' ')
.replace(';' , ' ');
或
tempPhrase1 = sentence.replace('.' , ' ');
tempPhrase2 = tempPhrase1.replace(',' , ' ');
tempPhrase3 = tempPhrase2.replace('!' , ' ');
tempPhrase4 = tempPhrase3.replace('?' , ' ');
tempPhrase5 = tempPhrase4.replace(':' , ' ');
tempPhrase = tempPhrase5.replace(';' , ' ');
答案 1 :(得分:3)
您可以将public class MyDialogFragment : MvxDialogFragment<MyDialogViewModel>
{
public MvxDialogFragment()
{
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
this.EnsureBindingContextIsSet(inflater);
var view = this.BindingInflate(Resource.Layout.dialog_view, null);
SetupToolbar(view);
return view;
}
private void SetupToolbar(View view)
{
Dialog.RequestWindowFeature((int)WindowFeatures.NoTitle);
toolbar = view.FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
toolbar.Title = null;
toolbar.InflateMenu(Resource.Menu.menu);
toolbar.MenuItemClick += HandlerMenuItemClick;
HasOptionsMenu = true;
}
public override bool HandlerMenuItemClick(object sender, Android.Support.V7.Widget.Toolbar.MenuItemClickEventArgs e)
{
switch (e.item.ItemId)
{
(...)
}
}
}
与正则表达式一起使用。
replaceAll